Jerry Nixon @Work: Accessing the UI thread from asynchronous handlers

Jerry Nixon on Windows

Monday, January 25, 2010

Accessing the UI thread from asynchronous handlers

The callback of asynchronous operations is not in the correct thread to access UI controls. Here’s the trick (in C#):

image

Get the code here: http://www.codepaste.net/6gm1zy

There’s not a lot to it. Handle the Completed event (I use an anonymous method, but a standard method works). The UI-oriented code is in an anonymous Action. When you Invoke() the Action, it executes the the correct context to access the UI.