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(()=>
{
TextBox1.Text="My Text";
}
);
CodeProject