3

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

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

        .. // do other work

        return Json(result );
    }
Anthony Potts
  • 8,842
  • 8
  • 41
  • 56
BobSwanson
  • 423
  • 2
  • 5
  • 18
  • Possible duplicate of [Should I unsubscribe from events?](http://stackoverflow.com/questions/4172809/should-i-unsubscribe-from-events) – Aravind Nov 30 '16 at 16:11

1 Answers1

3

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.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93