Unsubscribe anonymous method in C#

前端 未结 11 1388
夕颜
夕颜 2020-11-22 05:16

Is it possible to unsubscribe an anonymous method from an event?

If I subscribe to an event like this:

void MyMethod()
{
    Console.WriteLine(\"I di         


        
11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 06:12

    One simple solution:

    just pass the eventhandle variable as parameter to itself. Event if you have the case that you cannot access the original created variable because of multithreading, you can use this:

    MyEventHandler foo = null;
    foo = (s, ev, mehi) => MyMethod(s, ev, foo);
    MyEvent += foo;
    
    void MyMethod(object s, MyEventArgs ev, MyEventHandler myEventHandlerInstance)
    {
        MyEvent -= myEventHandlerInstance;
        Console.WriteLine("I did it!");
    }
    

提交回复
热议问题