Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe an anonymous function in Dispose method of a class?

I have a Class A...in it's constructor...I am assigning an anonymous function to Object_B's eventHandler.

How do I remove (unsubscribe) that from Dispose method of class A ?

Any help would be appreciated ! Thanks

Public Class A
{

public A()
 {

 B_Object.DataLoaded += (sender, e) =>
                {
                   Line 1
                   Line 2
                   Line 3
                   Line 4
                };
 }

Public override void Dispose()
{
  // How do I unsubscribe the above subscribed anonymous function ?
}
}
like image 949
Relativity Avatar asked Mar 16 '12 22:03

Relativity


1 Answers

You can't, basically. Either move it into a method, or use a member variable to keep the delegate for later:

public class A : IDisposable
{
    private readonly EventHandler handler;

    public A()
    {
        handler = (sender, e) =>
        {
           Line 1
           Line 2
           Line 3
           Line 4
        };

        B_Object.DataLoaded += handler;
     }

     public override void Dispose()
     {
        B_Object.DataLoaded -= handler;
     }
}
like image 126
Jon Skeet Avatar answered Nov 01 '22 16:11

Jon Skeet