Click here to Skip to main content
15,890,123 members
Articles / Mobile Apps / Windows Phone 7

Invoking Through the Dispatcher on Windows Phone and Metro

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
19 Apr 2012CPOL 21.4K   2   2
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.

C#
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.

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I attended Southern Polytechnic State University and earned a Bachelors of Science in Computer Science and later returned to earn a Masters of Science in Software Engineering. I've largely developed solutions that are based on a mix of Microsoft technologies with open source technologies mixed in. I've got an interest in astronomy and you'll see that interest overflow into some of my code project articles from time to time.



Twitter:@j2inet

Instagram: j2inet


Comments and Discussions

 
GeneralMy vote of 5 Pin
Leonardo Paneque19-Apr-12 11:58
Leonardo Paneque19-Apr-12 11:58 
GeneralMy vote of 5 Pin
Justin Cooney19-Apr-12 5:59
Justin Cooney19-Apr-12 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.