Tutorial :Subscribing to an event for the duration of a using block


I often come across the following code:

myService.SomeEvent += listener;  myService.DoSomething();  myService.SomeEvent -= listener;  

This is great, but it'd be nice if we could do this in a nicer way. I was thinking of doing something like:

using(EventScope.Start(myService.SomeEvent, listener)){      myService.DoSomething();  }  

Unfortunately this is prohibited by C# because myService.SomeEvent can only appear on the left hand side of a += or a -= (for good reason). My question is what other options do I have? Ideally I'd like this to be type safe, which rules out reflection and doing the following (which I've already implemented):

using(EventScope.Start(myService, "SomeEvent", listener){      myService.DoSomething();  }  

To be clear I'm not married to using the 'using' syntax, and arguable you could say that it's a perversion of the language. Other options would be appreciated!


There's probably a way to do this with cleaner syntax, but if you have a struct like this...

public struct ActionDisposable : IDisposable  {      private readonly Action _action;        public ActionDisposable(Action action)      {          _action = action;      }        public void Dispose()      {          _action();      }  }  

...and a method like this:

public static IDisposable EventScope(Action subscribe, Action unsubscribe)  {      subscribe();      return new ActionDisposable(unsubscribe);  }  

That would let you write code like this:

using (EventScope(() => myService.SomeEvent += listener, () => myService.SomeEvent -= listener))  {      myService.DoStuff();  }  

Or like this:

myService.SomeEvent += listener  using (new ActionDisposable(() => myService.SomeEvent -= listener))  {      myService.DoStuff();  }  


Are you worried that the event won't be unsubscribed because of an exception or something? If so you could use try/finally. Otherwise, I think the original way is best, and looks just fine to me.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »