Multithreading in Windows Phone 7 emulator: A bug
- by Laurent Bugnion
Multithreading is supported in Windows Phone 7 Silverlight applications, however the emulator has a bug (which I discovered and was confirmed to me by the dev lead of the emulator team): If you attempt to start a background thread in the MainPage constructor, the thread never starts. The reason is a problem with the emulator UI thread which doesn’t leave any time to the background thread to start. Thankfully there is a workaround (see code below). Also, the bug should be corrected in a future release, so it’s not a big deal, even though it is really confusing when you try to understand why the *%&^$£% thread is not &$%&%$£ starting (that was me in the plane the other day ;) This code does not work: public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait
| SupportedPageOrientation.Landscape;
var counter = 0;
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
Dispatcher.BeginInvoke(() =>
{
textBlockListTitle.Text = (counter++).ToString();
});
}
});
}
}
This code does work:
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait
| SupportedPageOrientation.Landscape;
var counter = 0;
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
Dispatcher.BeginInvoke(() =>
{
textBlockListTitle.Text = (counter++).ToString();
});
// NOTICE THIS LINE!!!
Thread.Sleep(0);
}
});
}
Note that even if the thread is started in a later event (for example Click of a Button), the behavior without the Thread.Sleep(0) is not good in the emulator. As of now, i would recommend always sleeping when starting a new thread.
Happy coding:
Laurent
Laurent Bugnion (GalaSoft)
Subscribe | Twitter | Facebook | Flickr | LinkedIn