Because Socket is a managed class, the IDisposable implementation guide states that Finalizer is not required. In fact, having a finalizer will actually delay the collection of object garbage, since it will call the finalizer during the first garbage collection, and garbage collects the object a second time garbage collection.
Regarding the event, which you probably want to cancel from the event in the Dispose method, since subscribing to the event will cause innerClass to contain a reference to the MyClass instance, if only the innerClass object is short-lived. See this question for more information on events and Dispose.
I think the following implementation will suffice for your scenario:
class MyClass : IDisposable { Socket m_listenerSocket = new Socket(); public void Dispose() { m_listenerSocket.Dispose(); innerClass.Notify -= Notify; } }
The part of your code that you commented on with “finalized unchanged code here” should only produce unmanaged resources, such as descriptors in the form of IntPtr , etc. After introducing SafeHandle in .NET 2.0, you rarely have to do this because you can wrap IntPtr in SafeHandle and then treat it as a managed resource.
PHeiberg
source share