Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove the listening of callback on anonymous method?

Tags:

c#

I wrote some class:

public class A 
{
    public A()
    {
        serviceAdapter.CompletedCallBackEvent += new EventHandler( foo );
        .
        .
        .
    }

    void foo(object sender, EventArgs e)
    {
        serviceAdapter.CompletedCallBackEvent -= new EventHandler( foo );
    }
}

Now, i want to change this callback listener with some anonymous - but i don't know how to remove the callback listener in the anonymous method .

class A
{
    public A()
    {
            serviceAdapter.CompletedCallBackEvent += delegate( object sender, EventArgs ee )
            {
                  ... need to remove the listener to the event. 
            }
    }
}
like image 563
Yanshof Avatar asked Feb 24 '23 23:02

Yanshof


2 Answers

You could simply assign your delegate/handler to a private variable.

private EventHander _handler = null;

public A()
{        
    _handler = delegate( object sender, EventArgs ee)
        {          
            ServiceAdapter.CompletedCallBackEvent -= _handler;
        };
    ServiceAdapter.CompletedCallBackEvent += _handler;
}
like image 64
Hasanain Avatar answered Feb 26 '23 11:02

Hasanain


You can't remove the anonymous delegate like that. See MSDN article on anonymous delegates. Also worth reading this article

You may be able to do:

     public A()
     {
         EventHandler myHandler = null;
         myHandler = new EventHandler(delegate(object s, EventArgs e)
             {
                 serviceAdapter.CompletedCallbackEvent -= myHandler;
             });

         serviceAdapter.CompletedCallBackEvent += myHandler;
     }
like image 33
IndigoDelta Avatar answered Feb 26 '23 11:02

IndigoDelta