BobSwanson BobSwanson - 8 months ago 50
ASP.NET (C#) Question

Subscribing to event in MVC controller

When subscribing to event in a controller, is there a need to unsubscribe? would not unsubscribing cause memory leaks? Why / why not?

public JsonResult Process(string data)
DataProcessor.Notify += (sender, args) =>
result = JsonConvert.SerializeObject(args);

.. // do other work

return Json(result );

Answer Source

First of all, the best and safest practice IMO is to always unsubscribe.

In this specific scenario, you should definitely unsubscribe, as your controller will have a shorter life than your (I guess) static DataProcessor class. Whenever a short lived object subscribes to a long living one, it will most likely cause memory leaks, as the long living object's event delegate list will hold a reference to your short living object.

I suggest you to unsubscribe in the controller's Dispose method.

If the DataProcessor is not a static class, but a field in your controller, you have to check the scope of that object. If it's a dedicated instance for this controller instance, than you can omit unsubscribing, because the two objects will most likely be GCd together.