Unsubscribe anonymous method in C#

C#DelegatesAnonymous Methods

C# Problem Overview


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

If I subscribe to an event like this:

void MyMethod()
{
	Console.WriteLine("I did it!");
}

MyEvent += MyMethod;

I can un-subscribe like this:

MyEvent -= MyMethod;

But if I subscribe using an anonymous method:

MyEvent += delegate(){Console.WriteLine("I did it!");};

is it possible to unsubscribe this anonymous method? If so, how?

C# Solutions


Solution 1 - C#

Action myDelegate = delegate(){Console.WriteLine("I did it!");};

MyEvent += myDelegate;


// .... later

MyEvent -= myDelegate;

Just keep a reference to the delegate around.

Solution 2 - C#

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;

Solution 3 - C#

From memory, the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods.

If you need to unsubscribe, you should either use a "normal" method or retain the delegate somewhere else so you can unsubscribe with exactly the same delegate you used to subscribe.

Solution 4 - C#

Since C# 7.0 local functions feature has been released, the approach suggested by J c becomes really neat.

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

So, honestly, you do not have an anonymous function as a variable here. But I suppose the motivation to use it in your case can be applied to local functions.

Solution 5 - C#

In 3.0 can be shortened to:

MyHandler myDelegate = ()=>Console.WriteLine("I did it!");
MyEvent += myDelegate;
...
MyEvent -= myDelegate;

Solution 6 - C#

Instead of keeping a reference to any delegate you can instrument your class in order to give the event's invocation list back to the caller. Basically you can write something like this (assuming that MyEvent is declared inside MyClass):

public class MyClass 
{
  public event EventHandler MyEvent;

  public IEnumerable<EventHandler> GetMyEventHandlers()  
  {  
      return from d in MyEvent.GetInvocationList()  
             select (EventHandler)d;  
  }  
}

So you can access the whole invocation list from outside MyClass and unsubscribe any handler you want. For instance:

myClass.MyEvent -= myClass.GetMyEventHandlers().Last();

I've written a full post about this tecnique here.

Solution 7 - C#

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.

Solution 8 - C#

If you want to be able to control unsubscription then you need to go the route indicated in your accepted answer. However, if you are just concerned about clearing up references when your subscribing class goes out of scope, then there is another (slightly convoluted) solution which involves using weak references. I've just posted a question and answer on this topic.

Solution 9 - C#

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!");
}

Solution 10 - C#

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

Solution 11 - C#

If the best way is to keep a reference on the subscribed eventHandler, this can be achieved using a Dictionary.

In this example, I have to use a anonymous method to include the mergeColumn parameter for a set of DataGridViews.

Using the MergeColumn method with the enable parameter set to true enables the event while using it with false disables it.

static Dictionary<DataGridView, PaintEventHandler> subscriptions = new Dictionary<DataGridView, PaintEventHandler>();

public static void MergeColumns(this DataGridView dg, bool enable, params ColumnGroup[] mergedColumns) {

    if(enable) {
        subscriptions[dg] = (s, e) => Dg_Paint(s, e, mergedColumns);
        dg.Paint += subscriptions[dg];
    }
    else {
        if(subscriptions.ContainsKey(dg)) {
            dg.Paint -= subscriptions[dg];
            subscriptions.Remove(dg);
        }
    }
}

Solution 12 - C#

There is a way to solve this by implementing the closure yourself instead of a lambda expression.

Assume that the class to be used as a capture variable is as follows.

public class A
{
    public void DoSomething()
    {
        ...
    }
}

public class B
{
    public void DoSomething()
    {
        ...
    }
}

public class C
{
    public void DoSomething()
    {
        ...
    }
}

These classes will be used as capture variables, so we instantiate them.

A a = new A();
B b = new B();
C c = new C();

Implement the closure class as shown below.

private class EventHandlerClosure
{
    public A a;
    public B b;
    public C c;

    public event EventHandler Finished;

    public void MyMethod(object, MyEventArgs args)
    {
        a.DoSomething();
        b.DoSomething();
        c.DoSomething();
        Console.WriteLine("I did it!");

        Finished?.Invoke(this, EventArgs.Empty);
    }
}

Instantiate the closure class, create a handler, then subscribe to the event and subscribe to the lambda expression that unsubscribes from the closure class's Finished event.

var closure = new EventHandlerClosure
{
    a = a,
    b = b,
    c = c
};
var handler = new MyEventHandler(closure.MyMethod);
MyEvent += handler;
closure.Finished += (s, e)
{
    MyEvent -= handler;
}

Solution 13 - C#

I discovered this quite old thread recently for a C# project and found all the answers very useful. However, there was one aspect that didn't work well for my particular use case - they all put the burden of unsubscribing from an event on the subscriber. I understand that one could make the argument that it's the subscribers job to handle this, however that isn't realistic for my project.

My primary use case for events is for listening to timers to sequence animations (it's a game). In this scenario, I use a lot of anonymous delegates to chain together sequences. Storing a reference to these isn't very practical.

In order to solve this, I've created a wrapper class around an event that lets you subscribe for a single invocation.

internal class EventWrapper<TEventArgs> {
	
	private event EventHandler<TEventArgs> Event;
	private readonly HashSet<EventHandler<TEventArgs>> _subscribeOnces;
	
	internal EventWrapper() {
		_subscribeOnces = new HashSet<EventHandler<TEventArgs>>();
	}

	internal void Subscribe(EventHandler<TEventArgs> eventHandler) {
		Event += eventHandler;
	}

	internal void SubscribeOnce(EventHandler<TEventArgs> eventHandler) {
		_subscribeOnces.Add(eventHandler);
		Event += eventHandler;
	}

	internal void Unsubscribe(EventHandler<TEventArgs> eventHandler) {
		Event -= eventHandler;
	}

	internal void UnsubscribeAll() {
		foreach (EventHandler<TEventArgs> eventHandler in Event?.GetInvocationList()) {
			Event -= eventHandler;
		}
	}

	internal void Invoke(Object sender, TEventArgs e) {
		Event?.Invoke(sender, e);
		if(_subscribeOnces.Count > 0) {
			foreach (EventHandler<TEventArgs> eventHandler in _subscribeOnces) {
				Event -= eventHandler;
			}
			_subscribeOnces.Clear();
		}
	}

	internal void Remove() {
		UnsubscribeAll();
		_subscribeOnces.Clear();
	}
}

The side benefit of having this in a class is that you can make it private and expose only the functionality you want. For example, only expose the SubscribeOnce (and not the Subscribe) method.

public class MyClass {
	
    private EventWrapper<MyEventEventArgs> myEvent = new EventWrapper<MyEventEventArgs>();
	
    public void FireMyEvent() {
        myEvent.Invoke(this, new MyEventEventArgs(1000, DateTime.Now));
    }
	
	public void SubscribeOnce(EventHandler<MyEventEventArgs> eventHandler) {
		myEvent.SubscribeOnce(eventHandler);
	}
	
	public class MyEventEventArgs : EventArgs {
		public int MyInt;
		public DateTime MyDateTime;
		
		public MyEventEventArgs(int myInt, DateTime myDateTime) {
			MyInt = myInt;
			MyDateTime = myDateTime;
		}
	}
}

The tradeoff here is more overhead for having an instance of this for each event, however in my scenario - this is an acceptable tradeoff to ensure that garbage gets collected efficiently and the code is more maintainable on the subscriber side. Full example here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEricView Question on Stackoverflow
Solution 1 - C#Jacob KrallView Answer on Stackoverflow
Solution 2 - C#J cView Answer on Stackoverflow
Solution 3 - C#Jon SkeetView Answer on Stackoverflow
Solution 4 - C#mazharenkoView Answer on Stackoverflow
Solution 5 - C#yanivView Answer on Stackoverflow
Solution 6 - C#hemmeView Answer on Stackoverflow
Solution 7 - C#casademoraView Answer on Stackoverflow
Solution 8 - C#BenjolView Answer on Stackoverflow
Solution 9 - C#Manuel MarholdView Answer on Stackoverflow
Solution 10 - C#user3217549View Answer on Stackoverflow
Solution 11 - C#LarryView Answer on Stackoverflow
Solution 12 - C#unggyuView Answer on Stackoverflow
Solution 13 - C#Bobby OsterView Answer on Stackoverflow