I wish to programatically unsubscribe to an event, which as been wired up.
I wish to know how I can unsubscribe to the EndRequest
event.
I'm not to sure how to do this, considering i'm using inline code. (is that the correct technical term?)
I know i can use the some.Event -= MethodName
to unsubscribe .. but I don't have a method name, here.
The reason I'm using the inline code is because I wish to reference a variable defined outside of the event (which I required .. but feels smelly... i feel like I need to pass it in).
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 I have, for me to handle errors in a ASP.NET
application.
NOTE: Please don't turn this into a discussion about ASP.NET error handling. I'm just playing around with events and using these events for some sample R&D / learning.
You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event.
To prevent your event handler from being invoked when the event is raised, simply unsubscribe from the event. In order to prevent resource leaks, it is important to unsubscribe from events before you dispose of a subscriber object.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.
It's not possible to unsubscribe that anonymous delegate. You would need to store it in a variable and unsubscribe it later:
EndRequestEventHandler handler = (sender, e) =>
{
if (some logic)
HandleCustomErrors(httpApplication, sender, e,
(HttpStatusCode)httpApplication.Response.StatusCode);
};
httpApplication.EndRequest += handler;
// do stuff
httpApplication.EndRequest -= handler;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With