Monday, July 5, 2010

#003 Invoking from UI Thread

Sometimes you just have to invoke a single line of code in the UI thread. The (very) old school way to to this is the following:

public delegate void VoidDelegate();
protected void WriteToConsole()
{
   Console.WriteLine("Invoked from UI Dispatcher");
}
...
View.Dispatcher.Invoke(new VoidDelegate(WriteToConsole));

To save time (and money), you can do this by using the System.Action delegate, which is a simple void delegate. By using anonymous methods, you additionally reduce the coding overhead by eliminating the need to create a separate method.

View.Dispatcher.Invoke(new 
Action(delegate{ 
Console.WriteLine("Invoked from UI 
Dispatcher"); })); 

Alternatively you can use lamda expressions for the delegate, which also reduces the coding by some chars...

View.Dispatcher.Invoke(new Action(() => 
  Console.WriteLine("Invoked from UI Dispatcher")));

No comments:

Post a Comment