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 :

.xaml
code
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: C#, WPF, Exception, Dispatcher, BeginInvoke, Thread
Dmitry said
Greate! It is simple and it works.
Thank you very much!
Ofir said
I’ve been looking for a soulution for so long!
Thanks a lot!!!!
Guillaume said
No problem.
I’m happy to see that this hack helped
G
programoo said
thank you so much I’ have been looking for this article for a long time too