2

I see this piece of code written by someone else:

 public class DynamicPageContent : IHttpModule
    {
        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            // it is necessary to 
            context.BeginRequest += new EventHandler(DynamicPageContent_BeginRequest);
        }
        //actual handler not pasting as it's meaningless for this question
}

As you can see the handler is registered but never deregistered. Wouldn't that create memory leak?

Jack
  • 7,433
  • 22
  • 63
  • 107
  • 2
    Simply - yes. Consider [this answer](http://stackoverflow.com/a/621177/1283124), assuming `DynamicPageContent_BeginRequest` is a instance method. Not all people agree, that his is actually a memory leak (this is different from C++ leaks in some sense), but as a general rule you should unsubscribe so that GC can collect object. – Ilya Ivanov Jun 04 '13 at 10:53
  • 1
    @IlyaIvanov: in *theory* should not, imo. As module is created once on App start (as much as I'm aware of) and always the *same* instance is refered during the request management. So this *should not* produce any memory leak, imo. – Tigran Jun 04 '13 at 10:56
  • @Tigran sorry, one side and quick note: could we agree on our definitions on what *memory leak* actually is? Wiki has a very generic definition, as *incorrectly manages memory allocations*, which I'm agree with – Ilya Ivanov Jun 04 '13 at 10:57
  • @IlyaIvanov: I in my *leak* definition I mean atually *leak* :) So nothing, *should*, damage program run. – Tigran Jun 04 '13 at 11:05

1 Answers1

2

Event handling can create leaks but only under certain conditions.

The thing to watch out for is when the subscribing object has a larger lifespan than the publishing object.

The thing to watch out for is when the publishing object has a larger lifespan than the subscribing object.

In this case they appear to be the same object and then it is not necessary or useful to unsubscribe. That would only clutter your code.

H H
  • 263,252
  • 30
  • 330
  • 514
  • +1 Correct. In presented circumstances, this should not produce any problem for the program, or a *leak*, in terms of unused and unreachable memory parts. There is always the *same* instance of module referenced in HTTP handling pipeline, and if the program "dies" all modules *should* "die" with it. – Tigran Jun 04 '13 at 11:45
  • @Tigran - yes, that this is a 'global' instance is another argument. – H H Jun 04 '13 at 12:06