Unsubscribe anonymous method in C#

前端 未结 11 1227
夕颜
夕颜 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:05

    One technique is to declare a variable to hold the anonymous method which would then be available inside the anonymous method itself. This worked for me because the desired behavior was to unsubscribe after the event was handled.

    Example:

    MyEventHandler foo = null;
    foo = delegate(object s, MyEventArgs ev)
        {
            Console.WriteLine("I did it!");
            MyEvent -= foo;
        };
    MyEvent += foo;
    
    0 讨论(0)
  • 2020-11-22 06:07

    if you want refer to some object with this delegate, may be you can use Delegate.CreateDelegate(Type, Object target, MethodInfo methodInfo) .net consider the delegate equals by target and methodInfo

    0 讨论(0)
  • 2020-11-22 06:09

    In 3.0 can be shortened to:

    MyHandler myDelegate = ()=>Console.WriteLine("I did it!");
    MyEvent += myDelegate;
    ...
    MyEvent -= myDelegate;
    
    0 讨论(0)
  • 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!");
    }
    
    0 讨论(0)
  • 2020-11-22 06:14

    Kind of lame approach:

    public class SomeClass
    {
      private readonly IList<Action> _eventList = new List<Action>();
    
      ...
    
      public event Action OnDoSomething
      {
        add {
          _eventList.Add(value);
        }
        remove {
          _eventList.Remove(value);
        }
      }
    }
    
    1. Override the event add/remove methods.
    2. Keep a list of those event handlers.
    3. When needed, clear them all and re-add the others.

    This may not work or be the most efficient method, but should get the job done.

    0 讨论(0)
提交回复
热议问题