Negative Aspects/Bad Practice of Static Event in C

2019-07-07 06:32发布

I reuse the code below a lot when I create events that will be used in different areas of an application. I find it really helpful and it makes events very easy to follow in the code. Is there any reason why this could be a bad idea? This is a bit broad, but basically is there a reason not to do this?

Event classes:

public delegate void FocusEventHandler(object source, FocusEventArgs e);

class FocusEvent
{
    public static event FocusEventHandler focusEvent;

    public static void Focus(bool status)
    {
        focusEvent(null, new FocusEventArgs(status));
    }
}

public class FocusEventArgs : EventArgs
{
    public bool Focused { get; set; }

    public FocusEventArgs(bool f)
    {
        Focused = f;
    }
}

So to fire the event, all I need is:

FocusEvent.Focus(false);

Thanks guys. This helps a lot. I really need to read up on memory usage.

标签: c# events static
2条回答
乱世女痞
2楼-- · 2019-07-07 07:10

A few years back, I worked on a large-scale Windows app that used static events. While investigating some memory usage issues, I discovered that no forms in the entire application were ever garbage collected. Pretty much every form subscribed to a static event, but never unsubscribed, causing them to stick around forever.

So yeah, the main reason not to do this is that you'll inevitably forget to unsubscribe from the event at some point, causing things to stick around for the lifetime of the application.

查看更多
Root(大扎)
3楼-- · 2019-07-07 07:18

The single biggest problem with static events is that you need to be really careful about unsubscribing from them. With an instance event, if you don't unsubscribe then you might end up keeping part of a graph artificially alive until the object with the event is released and is unreachable (making all the subscribers unreachable) - however, a static event never becomes unreachable. This means that any subscribers that don't unsubscribe will never be unreachable, and will never be garbage collected.

查看更多
登录 后发表回答