How can I unsubscribe from this .NET event?

I want to programmatically unsubscribe from an event that has been connected.

I want to know how I can unsubscribe from an EndRequest event.

I am not sure how to do this, given that I am using inline code. (is that the right technical term?)

I know I can use some.Event -= MethodName to unsubscribe .. but I don't have a method name here.

The reason I use the inline code is because I want to refer to a variable defined outside the event (which I need ... but it feels smelly ... I feel like I need to pass it).

Any suggestions?

Code Time ..

 public void Init(HttpApplication httpApplication) { httpApplication.EndRequest += (sender, e) => { if (some logic) HandleCustomErrors(httpApplication, sender, e, (HttpStatusCode)httpApplication.Response.StatusCode); }; httpApplication.Error += (sender, e) => HandleCustomErrors(httpApplication, sender, e); } private static void HandleCustomErrors(HttpApplication httpApplication, object sender, EventArgs e, HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError) { ... } 

This is just some sample code that I have for error handling in an ASP.NET application.

NOTE. Please do not include this in the discussion about ASP.NET error handling. I just play with events and use these events for some R & D / learning examples.

+8
c # event-handling events
source share
1 answer

Unable to unsubscribe from anonymous delegate. You will need to save it in a variable and unsubscribe later:

 EndRequestEventHandler handler = (sender, e) => { if (some logic) HandleCustomErrors(httpApplication, sender, e, (HttpStatusCode)httpApplication.Response.StatusCode); }; httpApplication.EndRequest += handler; // do stuff httpApplication.EndRequest -= handler; 
+11
source share

All Articles