-1

We have a nice tool by redgate called Memory Profiler. With it, we can easily check for memory leaks.

Now, in C# .Net 4.0, we're trying to figure the best way to handle events so not to have memory leaks but we cannot have any!! Everything we tried leave no trace! Here's what we tried so far:


    • In a limited scope, create a subscriber and publisher. Have subscriber subscribe to publisher's MyEvent
    • On dispose, the publisher sets its MyEvent to null
    • Exit scope
    • Result: no memory leak.

    • In a limited scope, create a subscriber and publisher. Have subscriber subscribe to publisher's MyEvent
    • On dispose, the publisher loops through MyEvent invocation list and remove each of then from MyEvent
    • Exit scope
    • Result: no memory leak.

    • In a limited scope, create a subscriber and publisher. Have subscriber subscribe to publisher's MyEvent
    • Exit scope
    • Result: no memory leak.

Now, there are various answers on SO on how we should manage events handlers, but none of them bring actual proof that there's any leak to be had. With our tool, we aim to have an actual result for an actual problem, but we can't have the problem in the first place.

Any idea how to ACTUALLY provoke a memory leak with events? Examples for .Net 4.5 or 4.6 will also do fine.

Jerther
  • 5,558
  • 8
  • 40
  • 59
  • 1
    For examples see [this](http://stackoverflow.com/q/12133551/1997232) or [this](http://stackoverflow.com/q/3662842/1997232) question. – Sinatr Dec 17 '15 at 15:09
  • From what I gather, there is no point in emptying MyEvent from within Publisher's Dispose(), right? – Jerther Dec 17 '15 at 15:41

1 Answers1

0

Using a static binding with += events will create a memory leak. It is a known bug that you have to manually use -= when binding with static.

With a quick google search, I can't find the bug post right now, but there was one posted for at least .NET up though v3.5.

Additionally, Microsoft confirms memory leaks and has a recommendation herein: https://msdn.microsoft.com/library/aa970850(v=vs.100).aspx

John S.
  • 1,937
  • 2
  • 18
  • 28