myLabs :: my Cool stuff

my Dev playground :: AIR, FLEX, Perl, JAVA, .NET, Ruby and many others

C# Dispatcher

Posted by Guillaume on December 5, 2007

As I’ve already said I’m pretty new to WPF and I got stuck  with an "System.InvalidOperationException" exception in one of my program.

Let’s say you want to write a text editor app and you want to schedule an auto save process every x second. The task is pretty easy you just have to create a Thread that start an infinite loop and within grab the text from the textbox, save it somewhere, and sleep for x second.

UI of our Text editor :



I you try this code it will CRASH with the message "The calling thread cannot access this object because a different thread owns it."
The UI thread owns the component we are trying to retrieve data from, and another thread can’t access it. The only way to deal with this problem is to use the main thread Dispatcher to place something in the  queue. Then we can ask the UI thread that have delegated, to asynchronously start a task (BeginInvoke).
We can also specify a priority for the task. There are 12 levels you can see here, but in our example since saving is very important I set the highest priority (10).

Here is the code that fix the problem :

Tags: , , , , ,


4 Responses to “C# Dispatcher”

  1. Dmitry said

    Greate! It is simple and it works.
    Thank you very much!

  2. Ofir said

    I’ve been looking for a soulution for so long!

    Thanks a lot!!!! 🙂

  3. Guillaume said

    No problem.
    I’m happy to see that this hack helped


  4. programoo said

    thank you so much I’ have been looking for this article for a long time too

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: