danroot

I've done what I think is a clever method for always safely raising events on the correct thread. But I wanted to run it by folks to see if I'm missing something:

internal class EventHandlerHelper
{
public static void SafeRaise<T>(EventHandler<T> handler, object sender, T args) where T : EventArgs
{
if (handler == null) return;
Control targetControl = handler.Target as System.Windows.Forms.Control;
if (targetControl != null && targetControl.InvokeRequired)
targetControl.Invoke(handler,sender, args);
else
handler(sender, args);
}
}

usage is:

EventHandlerHelper.SafeRaise<MyArgs>(MyEvent, this, args);

The idea is that the code prevents raising if no handlers are attached (handler == null), and invokes on the UI thread if currently on a different thread (InvokeRequired). Seems to work, but since this can be a tricky topic, I thought I'd post for expert advice =)

-dr


Re: Visual C# General Helper method for raising an event

Peter Ritchie

I would suggest using the AsyncOperation class, it is WinForms aware and allows you to support more than just GUI threads. It will handle getting back to the thread that created the AsyncOperation class. Calling of the delegate (wrapped in SendOrPostCallbac) is done through AsyncOperation.PostOperationCompleted()






Re: Visual C# General Helper method for raising an event

danroot

Thanks- very helpful. My example above would still cause problems if the event handler was not a control. I also am using this in .NET CF, which doesn't support AsyncOperation, but I'll look into it some more.