首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Deconstructor,Dispose不知道该使用什么

Deconstructor,Dispose不知道该使用什么
EN

Stack Overflow用户
提问于 2012-03-28 06:31:14
回答 1查看 1.7K关注 0票数 0

我在节目中遇到了一个小问题。我有一个类,其中包含一个套接字和一些声明的变量。

现在当我离开定义类的页面时,

代码语言:javascript
复制
Class someclass = new class;

我希望这个类被“销毁”,这样我就可以在另一个页面上打开一个具有相同端口/ip的新套接字。(现在端口和ip入口似乎被锁定在我没有解构/dispose/G.C的类中)

因为我有c++背景,这是我第一次使用c#。我不知道从哪里开始,因为在c++中,您只需调用析构函数。这将清理类并删除所有活动套接字/变量。但我如何在c#中完成这一任务。我读过一些关于一次性课的内容,但这并没有让事情变得更清楚。还有垃圾收集器和普通的解构函数。我不知道该使用什么,更重要的是如何使用它。

编辑1

如下所述:该项目是一个windows项目,它使用外部库创建一个套接字,并在windows和贝克霍夫PLC之间建立通信。

我在原始库的基础上创建了一个额外的层,以使我的变量更容易声明。额外的层如下所示:

代码语言:javascript
复制
public class TwincatVar<T> : IDisposable where T : IConvertible
{

    public AdsClient _AdsClient;
    private string _PlcVar;
    private uint _VarHandle;
    private T _Data;
    private DateTime _TimeStamp;
    private bool disposed = false;
    public EventHandler DataChanged;

    //constructor
    public TwincatVar(ref AdsClient AdsClient, string PlcVar)
    {
        //Hook up to the reference of AdsClient
        _AdsClient = AdsClient;

        _PlcVar = PlcVar;

    }

    public async Task InitFunction()
    {

            _VarHandle = await _AdsClient.GetSymhandleByNameAsync(_PlcVar);

            Debug.WriteLine(_VarHandle.ToString());

            _Data = await _AdsClient.ReadAsync<T>(_VarHandle);

            _AdsClient.AddNotificationAsync<T>(_VarHandle, AdsTransmissionMode.OnChange, 1000, this);

    }


    public T Data
    {

        get { return _Data; }
        set
        {
            _Data = value;
            _AdsClient.WriteAsync<T>(_VarHandle, value);
        }
    }

    public DateTime TimeStamp { get { return _TimeStamp; } }

    public void OnDataChangeEvent(T newData)
    {
        _TimeStamp = DateTime.Now;
        _Data = newData;

        //Raise the event
        if (DataChanged != null)
        {
            DataChanged(this, new EventArgs());
        }
    }

}

/*注意到了: IDisposable,这是因为我已经准备好实现它,但效果并不好。*/

代码语言:javascript
复制
public class TwincatDevice : IDisposable
{
    public AdsClient AdsClient;

    //Twincatdevice constructor
    public TwincatDevice(string amsNetIdSource, string ipTarget, string amsNetIdTarget, ushort amsPortTarget = 801)
    {
        AdsClient = new AdsClient(amsNetIdSource, ipTarget, amsNetIdTarget, amsPortTarget);
        AdsClient.OnNotification += DistributeEvent;
    }

    public static void DistributeEvent(object sender, AdsNotificationArgs e)
    {
        AdsNotification notification = e.Notification;


        switch (Type.GetTypeCode((notification.TypeOfValue)))
        {
            case TypeCode.Boolean: ((TwincatVar<bool>)notification.UserData).OnDataChangeEvent((bool)(notification.Value)); break;
            case TypeCode.Byte: ((TwincatVar<byte>)notification.UserData).OnDataChangeEvent((byte)(notification.Value)); break;
            case TypeCode.Int16: ((TwincatVar<short>)notification.UserData).OnDataChangeEvent((short)(notification.Value)); break;
            case TypeCode.Int32: ((TwincatVar<int>)notification.UserData).OnDataChangeEvent((int)(notification.Value)); break;
            case TypeCode.Single: ((TwincatVar<float>)notification.UserData).OnDataChangeEvent((float)(notification.Value)); break;
            case TypeCode.Double: ((TwincatVar<double>)notification.UserData).OnDataChangeEvent((double)(notification.Value)); break;
            case TypeCode.UInt16: ((TwincatVar<ushort>)notification.UserData).OnDataChangeEvent((ushort)(notification.Value)); break;
            case TypeCode.UInt32: ((TwincatVar<uint>)notification.UserData).OnDataChangeEvent((uint)(notification.Value)); break;
            case TypeCode.String: ((TwincatVar<string>)notification.UserData).OnDataChangeEvent((string)(notification.Value)); break;
        }
    }
}

在下面的代码中,我声明了我的“twincat变量”,我连接到一个datachange事件。此外,它们还连接到plc上的“.name”变量。

代码语言:javascript
复制
 public class MainPageViewModel : ViewModelBase
{
    public TwincatDevice client;       
    public Device _device0;
    public Device _device1;
    public Device _device2;  
    public Devices DeviceList = new Devices();
    public TwincatVar<string> Version;

    //View Model
    public MainPageViewModel()
    {
        //Create devices with initual values
        _device0 = new Device("Device Name", "Status", "Version");
        _device1 = new Device("Device Name", "Status", "Version");
        _device2 = new Device("Device Name", "Status", "Version");

        //Add devices to observablecollection
        DeviceList.Add(_device0);
        DeviceList.Add(_device1);
        DeviceList.Add(_device2);

        // create the connection with the beckhoff device
        _Create_TwincatDevice();
        _Create_Twincatvars();
    }

    ~MainPageViewModel()
    {
    }

    public void _Create_TwincatDevice()
    {
        // This is where the socket is openend !!

//Create TwincatDevice
        client = new TwincatDevice(amsNetIdSource: "192.168.11.216.1.1",
                                   ipTarget: "192.168.11.126",
                                   amsNetIdTarget: "192.168.11.126.1.1");        

    }

    public async Task _Create_Twincatvars()
    {
        // Create Twincat Variable
        Version = new TwincatVar<string>(ref client.AdsClient, ".Version");
        // Init Twincat Variable

        await Version.InitFunction();
        Version.DataChanged += (o, e) =>
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => { _device0.Version = Version.Data; });
        };



        // TwincatVar<type> Name = new TwincatVar<type>(reference to TwincatDevice, "Variable name PLC");

    }

}

}

最后但并非最不重要。在“页面后面的代码”(mainpage.xaml.cs)中,我创建了一个MainViewModel实例,并将其设置为数据文本以进行绑定。

代码语言:javascript
复制
private MainPageViewModel _MV;
_MV = new MainPageViewModel();
Device_listbox.DataContext = _MV.DeviceList;

我希望这能帮上忙,这样你们才能帮我:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-28 06:42:18

与C++不同,.NET不允许显式销毁由垃圾收集器分配的实例(类和装箱值类型/值类型作为通过垃圾回收器分配的类型的实例的成员)。这是因为垃圾收集器在认为是必要的(时间间隔、内存压力等)时会在您之后进行清理。如果需要在现场释放资源,则需要显式调用方法。您可以将此方法命名为类似于清理的方法。.NET已经提供了一个很好的模式来做到这一点。方法名为Dispose。(您可以实现具有零参数和空返回类型的Dispose方法,或者简单地实现IDisposable接口。将方法命名为“Dispose”而不是“清除”可以提供更好的工具支持,并允许使用“using语句”,在该语句中定义应该使用实例的作用域,并在作用域块的末尾自动调用Dispose方法。

有关实现Dispose方法的详细信息,以及如何与析构函数(以及固有的垃圾收集器)结合使用该方法的最佳实践,请参见http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.71).aspx

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9902262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档