Quick and Easy
A quick and easy way to spawn threads and update the UI from those threads is the following:
new Thread(() => { try { Thread.Sleep(3000); } finally { this.Dispatcher.BeginInvoke(() => { label1.Content = "testing within a thread"; }); } }).Start();
This code starts a new thread and runs it asynchronously to the main thread. The key here is the fact that there is no way to affect the main thread (that the UI is running on) directly from a spawned thread so you have to reference the parent (dispatcher) and call the ‘BeginInvoke’ method and pass it an anonymous function that runs on the same thread that the UI is running on.
Passing Parameters
Sometimes you need to get information in the function you are running. You can do this by passing in parameters into the anonymous function. For example:
new Thread((a) => { try { Thread.Sleep(3000); } finally { this.Dispatcher.BeginInvoke(() => { label1.Content = (string)a; }); } }).Start("test");
You have to remember to cast your parameter as it always comes in as an object and requires ‘un-boxing’.
Running external Functions
You can also start a thread on an external void method:
// The code starting the thread Thread thr = new Thread(new ParameterizedThreadStart(this.test)); thr.Name = "testthread"; thr.Start("1"); //The void method (object only parameters) public void test(object a) { while (runthread) { Thread.Sleep(3000); this.Dispatcher.BeginInvoke(() => { label1.Content += (string)a; }); } }
Notice that in the external method you can only have generic ‘object’ as the parameter and must then cast the data into the appropriate type afterwards.
