0

我已经在我的程序运行到一个小问题。我有一个类中有一个Socket和一些声明的变量。拆解,处置不知道该用什么

现在,当我离开这里被定义的类的页面,

Class someclass = new class; 

我希望类被“破坏”,所以,我可以用在其他相同的端口/ IP打开一个新的套接字页。 (现在的端口和IP地址似乎与类我不解构/配置/ g.c被锁定)

因为我有一个C++的背景下,这是用C#我的第一次。我不知道从哪里开始,因为在C++中你只需调用析构函数。这将清理你的班级并删除所有活动的套接字/变量。但我如何在c#中完成此操作。我已经阅读了关于Idisposable课程的一些内容,但这并没有让事情更清楚。还有垃圾收集器和正常的解构器。我不知道该使用什么,更重要的是如何使用它。


编辑1

正如评论如下表示:这个项目是一个Windows Phone的项目,使用一个外部库,用于创建一个套接字并建立在Windows Phone和Beckhoff公司PLC之间的通讯。

我创建原始库顶一个额外的层,使我更容易的变量声明。额外的层看喜欢这样的:

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的那是因为我已经尝试过媒体链接来实现它,但是这并不能很好地工作。 */

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”变量。

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的一个实例,并将其设置为DataContext的结合。

private MainPageViewModel _MV; 
_MV = new MainPageViewModel(); 
Device_listbox.DataContext = _MV.DeviceList; 

我希望这有助于使你们能帮助我:)

+0

能否请你告诉更多的源代码中的最佳实践如何插座被建造。你是否使用任何指针来创建套接字并连接到它? 你可以在你的类上使用Dispose模式来处理套接字。在Dispose方法中,你可以把你的清理代码。然后在Usage类中使用Using()块。 – Zenwalker 2012-03-28 06:34:50

+0

@zenwalker这有点问题,因为套接字是在外部库中创建的,而我所做的唯一事情就是声明一个创建套接字的类。我用的是libary可以在这里找到: http://ads.codeplex.com/ 其用于连接PLC的使用广告协议(在C#中的正常插座上方), – 2012-03-28 06:40:29

+0

是请不要显示的代码如何使用该API库创建,连接和关闭套接字。那么我们可以帮助你更多。 – Zenwalker 2012-03-28 06:41:57

回答

3

相比于C++ ,. NET不允许被垃圾收集程序分配的一个实例的明确破坏(类和装箱值类型/值类型作为通过垃圾回收器分配的类型实例的成员)。这是因为垃圾收集器需要照顾你后清理的时候它认为所必要的(定时间隔,内存压力等)。如果您需要在现场释放资源,则需要显式调用方法。您可以将此方法命名为Cleanup。 .NET已经有了一个很好的模式来实现这一点。方法名称是Dispose。 (你可以实现一个Dispose方法,它具有零参数和void返回类型,或者简单地实现IDisposable接口。将方法命名为Dispose而不是Cleanup可以为你提供更好的工具支持,并允许使用using语句',其中定义的范围,其中,您的实例应被使用并且自动调用在范围块的末尾Dispose方法。

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

+0

除了调用Dispose方法之外,还应该实现'IDisposable'。如果你的类是可继承的,通常的做法是实现'IDisposable.Dispose(void)'调用一个受保护的'Dispose(bool)'函数来完成实际的处理。 – supercat 2012-03-28 16:20:09