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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With