# Helper methods for working with the WPF Dispatcher

I've written the following small helper class for use in my WPF applications. It comes up from time to time that I need to display message boxes, or otherwise interact with the UI from a non UI thread.

public static class ThreadContext
{
{
if (Application.Current.Dispatcher.CheckAccess())
{
action();
}
else
{
Application.Current.Dispatcher.Invoke(action);
}
}

{
if (Application.Current.Dispatcher.CheckAccess())
{
action();
}
else
{
Application.Current.Dispatcher.BeginInvoke(action);
}
}
}


Here is a small example of how this might be used.

public static MyFunction()
{
delegate()
{
MessageBox.Show("Hello world!");
});
}


This works, but declaring the delegate the way I do seems overly verbose.

Is there anyway to make the syntax less verbose while still allowing for arbitrary functions to be passed? Is there anything else that you would suggest to improve this solution -- including an entirely different solution?

-

anonymous methods to the rescue! I saw somebody griping about this syntax recently on a blog and found it unfortunate they were dissimenating this. The cleaner new and happy way to define a delegate, is quite simply:

The method signature without a name or types, so for example:

Sum(int a, int b)


becomes:

(a, b)


Follow this with our trusty lambda operator => and then our method body! This may be in a statement block between our trusty {} or just in a single line the same way you can put a single line after an if or while etc.

So in conclusion there are 3 ways to create a method:

Standard (must be declared as class member level):

public int Sum(int a, int b)
{
return a+b;
}


Delegate (can be declared and instantiated as a method local):

delegate(int a, int b)
{
return a+b; // god help me if this syntax is correct, I haven't created a delegate in years
}


Anonymous method (can be declared and instantiated as a method local):

(a, b) => { return a+b; };


ThreadContext.InvokeOnUiThread(
delegate()
{
MessageBox.Show("Hello world!");
});


In anonymous method format becomes:

ThreadContext.InvokeOnUiThread(() => { MessageBox.Show("Hello world!"); });


Or if you prefer:

Action actionToInvokeOnUiThread = () => { MessageBox.Show("Hello world!"); };