This code provides SafeTrigger extension methods as a way of triggering events in a thread safe way.
For details on usage, a discussion of reasons and alternatives, and a full solution download see my article on
safely triggering events[
^]
Multiple overloads are provided for convenience to allow for as many triggering scenarios as possible.
public static class SafeTriggerExtensions
{
public static void SafeTrigger(this EventHandler eventToTrigger, Object sender)
{
if (eventToTrigger != null)
{
eventToTrigger(sender, EventArgs.Empty);
}
}
public static void SafeTrigger(this EventHandler eventToTrigger, Object sender, EventArgs eventArgs)
{
if (eventToTrigger != null)
{
eventToTrigger(sender, eventArgs);
}
}
public static TReturnType SafeTrigger<TReturnType>(this EventHandler eventToTrigger, Object sender,
EventArgs eventArgs, Func<EventArgs, TReturnType> retrieveDataFunction)
{
if (retrieveDataFunction == null)
{
throw new ArgumentNullException("retrieveDataFunction");
}
if (eventToTrigger != null)
{
eventToTrigger(sender, eventArgs);
TReturnType returnData = retrieveDataFunction(eventArgs);
return returnData;
}
else
{
return default(TReturnType);
}
}
public static void SafeTrigger<TEventArgs>(this EventHandler<TEventArgs> eventToTrigger, Object sender,
TEventArgs eventArgs) where TEventArgs : EventArgs
{
if (eventToTrigger != null)
{
eventToTrigger(sender, eventArgs);
}
}
public static void SafeTrigger<TEventArgs>(this EventHandler<TEventArgs> eventToTrigger,
Object sender) where TEventArgs : EventArgs, new()
{
if (eventToTrigger != null)
{
eventToTrigger(sender, new TEventArgs());
}
}
public static TReturnType SafeTrigger<TEventArgs, TReturnType>(this EventHandler<TEventArgs> eventToTrigger,
Object sender,
Func<TEventArgs, TReturnType> retrieveDataFunction)
where TEventArgs : EventArgs, new()
{
if (retrieveDataFunction == null)
{
throw new ArgumentNullException("retrieveDataFunction");
}
if (eventToTrigger != null)
{
TEventArgs eventArgs = new TEventArgs();
eventToTrigger(sender, eventArgs);
TReturnType returnData = retrieveDataFunction(eventArgs);
return returnData;
}
else
{
return default(TReturnType);
}
}
public static TReturnType SafeTrigger<TEventArgs, TReturnType>(this EventHandler<TEventArgs> eventToTrigger,
Object sender, TEventArgs eventArgs,
Func<TEventArgs, TReturnType> retrieveDataFunction)
where TEventArgs : EventArgs
{
if (retrieveDataFunction == null)
{
throw new ArgumentNullException("retrieveDataFunction");
}
if (eventToTrigger != null)
{
eventToTrigger(sender, eventArgs);
TReturnType returnData = retrieveDataFunction(eventArgs);
return returnData;
}
else
{
return default(TReturnType);
}
}
}