简体   繁体   中英

Will several bindings of static/global Event handler to Events in a class, lead to a thread/memory leak?

I have a class with EventHandler bindings at the constructor, that will be instantiated thousand times within application lifecycle. The question is: Will this approach leads to memory/thread leaks?

I did this way (code below), because I need to be notified every time SomeMethod() runs, whatever instance run it. Foo class (the publisher) will be short-lived, however the handlers will live until the application closes.

I ask this because, when working with Windows Forms, each form can hold several event handlers/delegates and everything is fine because all those delegates are inside the form and will be disposed when the form closes. But how about static event handlers/delegates, that could be even on separate projects?

Will I need to write a destructor to detach those event handlers? Should I go with Weak Event Pattern ?

Restriction: I must do this with .NET 3.5. I know I could do this with TPL, setting a "Fire and Forget" Task.

Thank you in advance.

Code:

public class Foo
{
    public event EventHandler SomeEvent;
    public Foo()
    {
        SomeEvent += FooHandlers.Foo_SomeEvent1;
        SomeEvent += FooHandlers.Foo_SomeEvent2;
    }

    public void RaiseEvents(EventHandler evt, EventArgs args)
    {
        var eventObj = evt; 
        var listeners = eventObj.GetInvocationList();
        foreach (var listener in listeners)
        {
            var method = (EventHandler)listener;
            ThreadPool.QueueUserWorkItem(callBack => method(this, args));
            // Handlers will do a lot of things, so I don't want
            // them blocking the Main thread
        }
    }

    public void SomeMethod()
    {
        // do something here
        RaiseEvents(SomeEvent, new EventArgs());
    }
}

public static class FooHandlers
{
    public static void Foo_SomeEvent1(object sender, EventArgs e)
    {
        //do something here
    }
    public static void Foo_SomeEvent2(object sender, EventArgs e)
    {
        //do something different here
    }
}

Since your handlers are static methods the delegate you're adding to the event doesn't have an object instance, so there is no object instance being kept alive for the duration of the object with the event.

And even if you did use an object instance to attach the handler, it wouldn't be a problem, because the object with the event is short lived. The only time there is a problem is when the object with the event is long lived, and the object that has a handler to itself assigned is short lived, and consumes a lot of resources to keep alive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM