I usually use Dispatcher.Invoke when i need to access some UI elements from background thread. Recently i had to change other’s written sources and i saw that same tasks he accomplishes with constructions like:
Dispatcher.Invoke((ThreadStart)delegate
{
//some code that uses controls from UI
});
When should i use such code instead of Dispatcher.Invoke/BeginInvoke and why?
That does use
Dispatcher.Invoke– it’s not an “instead of”. That code is just usingThreadStartas a way of telling the compiler the delegate type to convert the anonymous method to.It’s equivalent to:
Personally I’d use
Actioninstead ofThreadStarthere as you’re not actually starting a thread, but it’s a pretty arbitrary choice. Ignore the fact that it’s calledThreadStart– it’s just a delegate with a void return type and no parameters.EDIT: The reason you have to specify a delegate type is that the compiler can’t convert an anonymous function (i.e. an anonymous method or a lambda expression) to just
Delegate, which is the argument type ofDispatcher.Invoke.One workaround for this is to write an extension method:
You can then use:
and the compiler knows to convert the lambda expression to
Action.