In my current project, I find myself using Dispatcher.Invoke
a lot. Before each call I test if the current dispatcher is the right one. I want to write a wrapper class like so:
class SafeRunner
{
//From the thread we always need to run on
public static System.Windows.Threading.Dispatcher disp;
public static void Run<T>(Action<T> f, T arg)
{
if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
{
disp.Invoke(f, arg);
}
else
{
f(arg);
}
}
public static void Run<T1, T2>(Action<T1,T2> f, T1 arg1, T2 arg2)
{
if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
{
disp.Invoke(f, arg1, arg2);
}
else
{
f(arg1, arg2);
}
}
public static void Run<T1, T2, T3>(Action<T1,T2,T3> f, T1 arg1, T2 arg2, T3 arg3)
{...}
public static void Run<T1, T2, T3, T4>(Action<T1,T2,T3,T4> f, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{...}
}
And I can use it like this:
SafeRunner.Run<string,string>((a,b) => {
doSomething(a,b);
doSomethingElse(a);
// Maybe a few more lines here
}, "Hello", "World");
This works, but doesn't feel right. Is there a better way?
SafeRunner.Run(doSomething, "Hello", "World")
. The methodgroup/delegate should match the parameters already, after all. That makes it closer to the dispatcher's syntax too, which is probably a good thing. – Magus Apr 1 '14 at 18:50