Generic WPF Dispatcher

Howdy! In a medium to large WPF application, it is fairly common required to do some background stuff and update the UI asynchronously. You could use the BackgroundWorker class to do this, you could use the Dispatcher object to do this too. Most of the people know how to use the Dispatcher and for those who do not, this link will surely help http://msdn.microsoft.com/en-us/magazine/cc163328.aspx.

Rather than peppering the Dispatcher code all over the application, it would be nice to have it in a single place. This can be achieved using extension methods on the Dispatcher class. Below is some code which can be used as is to make your Dispatcher generic enough to do most of the stuff.

internal static class TDFDispatcher
{
internal static void Dispatch(this Dispatcher source,Nullable<DispatcherPriority> priority,Action invokedDelegate)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate);
}
else
{
invokedDelegate();
}
}
}

internal static void Dispatch<T>(this Dispatcher source, Nullable<DispatcherPriority> priority, Action<T> invokedDelegate,T arg)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate,arg);
}
else
{
invokedDelegate(arg);
}
}
}

internal static TResult Dispatch<T,TResult>(this Dispatcher source, Nullable<DispatcherPriority> priority, Func<T,TResult> invokedDelegate, T arg)
{
TResult result = default(TResult);
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
result = (TResult)source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate, arg);
}
else
{
result = invokedDelegate(arg);
}
}
return result;
}


You can certainly come up with even more permutations and combinations to enhance this class.



Happy Programming!

Abhang Rane


No comments :

Post a Comment

Leave a Comment...