Friday, July 12, 2013

Windows Phone Tip: Updating the UI from an Asynchronous Thread

One of the most common tasks you need to perform in a Windows Phone application is updating the UI from a separate thread. For example, you may be download some content asynchronously using a WebClient class and when the operation is completed, you want to update the UI with the content that was downloaded. Updating the UI directly from an asynchronous thread is not allowed, as UI controls are not thread-safe.  

The easiest way to update the UI from an asynchronous thread is to use the Dispatcher class. To determine if you can update an UI directly, you can use the CheckAccess() method. If this method returns a true, it means you can directly update the UI. Else, you have to use the BeginInvoke() method of the Dispatcher class to update the UI in a thread-safe manner. The following code snippet makes this clear:

    if (Dispatcher.CheckAccess() == false)
    {
        //---you have to update the UI through the
        // BeginInvoke() method---
        Dispatcher.BeginInvoke(() =>
            txtStatus.Text = "Something happened..."
        );
    }
    else
    {
        //---you can update the UI directly---
        txtStatus.Text = "Something happened..."
    }

If you have more than one statement to perform in the BeginInvoke() method, you can group them into a method and call it like this:


        private void UpdateUI(String text)
        {
            txtStatus.Text = text;
            btnLogin.Content = text;
        }
        ...
        ...

            Dispatcher.BeginInvoke(() =>
                UpdateUI("Something happened...")

            );

1 comment:

JPCP said...

With The beauty of Lambda Expressions, you can do this to avoid to create a new method just for using two statements inside a BeginInvoke:

Dispatcher.BeginInvoke(() =>
{
LogInButton.IsEnabled = true;
Progress.Visibility = System.Windows.Visibility.Collapsed;
});