patterncsharpMinor
Same function, variable parameters and types with lambda
Viewed 0 times
samevariablewithfunctiontypesandparameterslambda
Problem
In my current project, I find myself using
And I can use it like this:
This works, but doesn't feel right. Is there a better way?
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(Action f, T arg)
{
if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
{
disp.Invoke(f, arg);
}
else
{
f(arg);
}
}
public static void Run(Action 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(Action f, T1 arg1, T2 arg2, T3 arg3)
{...}
public static void Run(Action f, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{...}
}And I can use it like this:
SafeRunner.Run((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?
Solution
A couple of things I notice, and they are both around the if statements
I would flip the if statements around so that they are checking the positive test. I would also put the
I would flip the if statements around so that they are checking the positive test. I would also put the
disp on the right side of the ==. You can eliminate the else statement, all it really does is clutters up the code.if (System.Windows.Threading.Dispatcher.CurrentDispatcher == disp)
{
f(arg);
return;
}
disp.Invoke(f, arg);Code Snippets
if (System.Windows.Threading.Dispatcher.CurrentDispatcher == disp)
{
f(arg);
return;
}
disp.Invoke(f, arg);Context
StackExchange Code Review Q#45969, answer score: 3
Revisions (0)
No revisions yet.