rkp
rkp

Reputation: 11

unsubscribing events from class?

I need bit of advise on best practice for this type of scenario. I searched but dont find any satisfying answer.

We use a 3rd party (.net) DLL in our winforms project. It raises some events and we subscribe to. Question is , do i need to explicitly unsubscribe these events in my class ?

BTW we both use .net framework 4. Thanks for the advise.

some sample code ...

public class MyClientCode: IDisposable
{
   private readonly 3rdParty.TheirClass _theirClass;
   public MyClientCode()
  {
     _theirClass = new _theirClass()
     _theirClass.ReadData += ReadDataEvent;
  }

  public void SomeOtherMethod()
  {
           //some other code
  }

  public void ReadDataEvent()
  {
    //some code
  }

  public void Dispose()
  {
    _theirClass.ReadData -= ReadDataEvent;
  }
}

and in the button click event, i do ...

 MyClientCode code = new MyClientCode();
 code.SomeOtherMethod();

Upvotes: 1

Views: 1294

Answers (1)

Cyral
Cyral

Reputation: 14153

If you don't unsubscribe, the object that subscribed to the event will not be garbage collected (it will be kept in memory). This can create memory leaks and lead to excessive memory usage.

However, if the event has a shorter or same lifetime as the class that contains it, in your case, the memory will be collected properly. If you have another object reference a non-private event, then you will run into issues.

See MSDN:

Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.

Note that you don't need to unsubscribe if you are exiting your application, only in cases where it shouldn't be held in memory. (For example, when you close a window in your application, you should unsubscribe from any events, or else the window will still be held in memory.) If the containing object is destroyed manually, the events will also be destroyed.

Upvotes: 4

Related Questions