Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative Aspects/Bad Practice of Static Event in C#

Tags:

c#

static

events

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.

like image 979
Jonesopolis Avatar asked Dec 05 '22 11:12

Jonesopolis


1 Answers

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.

like image 168
Marc Gravell Avatar answered Dec 24 '22 03:12

Marc Gravell