Raising events

 Hello all,

 

When you use events in C# you declare an event:

public event EventHandler SomeEvent;

 

 

Do you like to repeat this code?

if (SomeEvent != null)
{
	SomeEvent(this, EventArgs.Empty);
}

FWI, this is not thread safe, you can see an example at MSDN:

msdn.microsoft.com/en-us/library/db0etb8x.aspx

 

Here some extension methods to stop repeating this.

[DebuggerStepThrough]
public static void Raise<T>(this EventHandler<T> handler, object sender, T eventArgs) where T : EventArgs
{
    //Copy to a temporary variable to be thread-safe.
    EventHandler<T> temp = handler;
    if (temp != null)
    {
        temp(sender, eventArgs);
    }
}

 

[DebuggerStepThrough]
public static void Raise<T>(this EventHandler<T> handler, object sender) where T : EventArgs
{
	handler.Raise(sender, default(T));
}

[DebuggerStepThrough]
public static void Raise<T>(this EventHandler<T> handler) where T : EventArgs
{
	handler.Raise(null);
}

[DebuggerStepThrough]
public static void Raise(this EventHandler handler, object sender, EventArgs eventArgs)
{
    //Copy to a temporary variable to be thread-safe.
    EventHandler temp = handler;
    if (temp != null)
    {
        temp(sender, eventArgs);
    }
}

[DebuggerStepThrough]
public static void Raise(this EventHandler handler, object sender)
{
    handler.Raise(sender, EventArgs.Empty);
}

[DebuggerStepThrough]
public static void Raise(this EventHandler handler)
{
    handler.Raise(null, EventArgs.Empty);
}

 

And now you can raise the event like so:

SomeEvent.Raise(this);

 

Enjoy,

Ofir

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com