Wednesday, September 22, 2010

WPF asynchronous callback on UI thread


SynchronizationContext class present in the System.Threading namespace helps us to avoid cross threading issue of the UI element while the asynchronous calls.

DispatcherSynchronizationContext.Current gives the reference to the current UI thread and accepts all the UI component gets update in this synchronization context.

The way to achieve is, in the main UI control constructor assigned the member variable of type SynchronizationContext with the DispatcherSynchronizationContext.Current. While getting the async (another thread) callback due to some async server or any other operation, make sure the UI gets updated in the saved member variable SynchronizationContex. example

public class TestUI : UserControl/Window
{
private SynchronizationContext _eventHandlerViewsContext;
public TestUI()
{
_eventHandlerViewsContext = DispatcherSynchronizationContext.Current;
}
public void AsyncCallback(IAsyncResult result)
{
     SendOrPostCallback callback = new SendOrPostCallback(delegate(object obj)
    {
         //UI code or function which updates the UI
    });
   _eventHandlerViewsContext.Post(callback, null); 
}