开发者

Should I use event aggregator only to prevent memory leaks?

开发者 https://www.devze.com 2023-03-20 18:06 出处:网络
We consider to use the Prism event aggregator for the purpose of reducing memory leaks due to 开发者_JAVA技巧event references.

We consider to use the Prism event aggregator for the purpose of reducing memory leaks due to 开发者_JAVA技巧event references.

  1. Is this for itself a valid reason to use this pattern? The other benefits are not interesting for us now. We plan to use it between model components and not UI.

  2. Our problem was that some developers forgot to unregister events. I saw that Prism has one flavour which uses weak references but it has limitations. The other flavour forces to explicitly Unsubscribe(), which again can be forgotten. So how is it better?


Our problem was that some developers forgot to unregister events

If this is your problem, switching to the Prism event aggregator (or, using any other implementation) won't improve things.

Adding a new dependency with a new, non-trivial, usage pattern into a messy situation isn't going to tidy it up at all.

What you need is to clean up your code.

Instead of new code libraries, I'd suggest looking into static analysis tools like fxCop (aka Code Analysis), Gendarme and NDepend. All of these are able to detect some situations where events are not unhooked or where IDisposable is not implemented properly.

Using static analysis, you can dispassionately identify code that needs cleanup. Throw in use of a memory profiler (like dotTrace Memory) and you'll be able to find the worst offenders and clean them up promptly.

Update

In answer to the question in the comment below:

What do you suggest as a good pattern for ensuring that events get unhooked?

In can be difficult to make sure that all events are unsubscribed - but given the way that events are implemented (see CLR via C# for details), you can cheat a little by ensuring all event subscriptions are discarded.

Instead of

public event EventHandler<Fu> FuBar;

handle the event subscription yourself, like this:

public event EventHandler<Fu> FuBar {
    add { mFuBar += value; }
    remove { mFuBar -= value; }
}

private EventHandler<Fu> mFuBar;

Then, implement IDisposable on your class, and in your Dispose() method set mFuBar to null, discarding the subscriptions. FxCop (and other tools) can then tell you if you are failing to Dispose of the class.

0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消