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 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 :