How to cancel anonymous function in class Dispose method?

I have a class A ... there is a constructor in it ... I assign an anonymous function Object_B eventHandler.

How to remove (unsubscribe) that from class A's Dispose method?

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 ?
}
}
+5
source share
3 answers

You cannot, in principle. Either move it to a method, or use a member variable to save the delegate 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;
     }
}
+7
source

The right way to do this is to use Rx extensions. Watch the video here:

http://msdn.microsoft.com/en-us/data/gg577611

I found the movie "blues" especially useful.

0
source

This is an alternative without using a handler variable.

Public Class A
{

 public A()
  {

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

  Public override void Dispose()
  {
   if(B_Object.DataLoaded != null)
   {
     B_Object.DataLoaded -=
         (YourDelegateType)B_Object.DataLoaded.GetInvocationList().Last();
       //if you are not sure that the last method is yours than you can keep an index
       //which is set in your ctor ...
   }
  }
 }
0
source

All Articles