Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Invoking Through the Dispatcher on Windows Phone and Metro

0.00/5 (No votes)
19 Apr 2012 1  
Invoking through the Dispatcher on Windows Phone and Metro

On Windows Platforms, there is a rule that you cannot modify UI elements from secondary threads. On Microsoft's XAML based platforms, there is a member that exists on most UI objects called the Dispatcher that can be used to marshal a call to the proper thread.

On Windows Phone 7 and Windows 8, the way you go about calling this thread differs. I was recently working with some code that needed to compile for both platforms and wanted to minimize the amount of code that had to be wrapped in conditional compilation blocks. To do this, I made a single method to handle my dispatching. The method itself contains conditional compilation blocks but because of this method, I didn't need the blocks when I needed to perform operations on the UI thread.

public void DispatchInvoke(Action a)
{
#if SILVERLIGHT
    if (Dispatcher == null)
        a();
    else
        Dispatcher.BeginInvoke(a);
#else
    if ((Dispatcher != null) && (!Dispatcher.HasThreadAccess))
    {
        Dispatcher.InvokeAsync(
                    Windows.UI.Core.CoreDispatcherPriority.Normal, 
                    (obj, invokedArgs) => { a(); }, 
                    this, 
                    null
         );
    }
    else
        a();
#endif
}

The code will compile for both Windows Phone 7 and Windows 8 Metro without any alterations. Using the code is the same regardless of which of the two platforms you are using.

DispatchInvoke(()=>
  {
    //your operations go here
    TextBox1.Text="My Text";
  }
);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here