Sunday 23 December 2007

Updating the UI from a Secondary Thread

[Full article]In my January 2004 column I discussed the use of delegates to execute a method asynchronously. I showed you that it's relatively easy to call BeginInvoke on a delegate object from the code behind a Windows® Form in order to dispatch an asynchronous method call. You also saw how to set up a callback method that fires automatically when the asynchronous method call completes its execution. However, I stopped short of talking about how you should update the UI to tell the user that the work is complete.
Updating user interface elements from a secondary thread in Windows Forms is tricky because a secondary thread is not allowed to read or write property values directly from a form or any of its child controls. This restriction exists because form objects and control objects in Windows Forms are not thread-safe. The only thread that's allowed to directly access a property value of a form or one of its controls is the primary UI thread. You must learn how to update the user interface without breaking this rule.
The technique you're going to learn here involves writing code to switch control to the primary UI thread from the secondary thread where it's executing—a process known as marshaling. This will allow you to update the UI safely and reliably. Once you switch control from a secondary thread to the primary UI thread, you are free to change any property values of a form and its child controls.

No comments: