WPF Reflections

Jun 20 2008   1:25PM GMT

WPF – how to use an anonymous method with Dispatcher

Mark Shurmer Profile: MarkWPF

Have you ever been in the situation where you’d thought you were in the UI thread nice and safely, but got the exception message:

The calling thread cannot access this object because a different thread owns it”

What this means is that you have created an object on a thread (usually UI thread), and are then trying to access it from another thread at runtime.
Maybe from a worker thread running an event handler.

To fix it, you need to use the very handy Dispatcher class, which will marshall your call to the correct thread.
You need to use the BeginInvoke (asynchronous) or the Invoke method.

However, you don’t want to have huge numbers of delegate definitions all over your code, so use an anonymous method instead.
The trick is to make sure the returned type from the anonymous delegate is one that matches what the Invoke method expects 🙂
If the correct thread happens to be the UI thread you can do the following:

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, (DispatcherOperationCallback)delegate(object arg)
// do sommat
return null;

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: