Written by
on
on
Invoking generic methods on the UI thread in C# WPF
Everybody knows that UI operations can be executed only on the UI thread. So sometimes when calls can originate from other threads as well, it is a must to check the actual thread and switch it for the called method when necessary. There are a lot of examples out there that explains how a simple Action can be invoked, however I find this little code snippet below very useful. It shows how a generic method with input and output parameters can be invoked.
public TOut MyGenericMethod<TIn, TOut>(TIn elem)
{
if (!Application.Current.Dispatcher.CheckAccess())
{
var func = new Func(MyGenericMethod<TIn, TOut>);
return (TOut)Application.Current.Dispatcher.Invoke(func, elem);
}
return default(TOut);
}
Note that some of the overloads of the Invoke method accepts DispatcherPriority as an argument. In our case, it is not set and its default value is Normal.