I have the following code in a very simple Silverlight 4 app.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var result = string.Empty;
var mutex = new AutoResetEvent(false);
var wc = new WebClient();
wc.DownloadStringCompleted += (s, args) => {
result = args.Result;
mutex.Set();
};
wc.DownloadStringAsync(new Uri("http://localhost/SilverlightApplication2.Web/SilverlightApplication2TestPage.aspx", UriKind.Absolute));
mutex.WaitOne();
MessageBox.Show(result);
}
For whatever reason the mutex.Set() is never called so the mutex.WaitOne() just locks up. What am I missing? I have also tried ManualResetEvent.
Thanks,
Randall
UPDATE1:
If I do the following it works as expected.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(GetIt);
}
private void GetIt(object state)
{
var result = string.Empty;
var mutex = new AutoResetEvent(false);
var wc = new WebClient();
wc.DownloadStringCompleted += (s, args) => {
result = args.Result;
mutex.Set();
};
wc.DownloadStringAsync(new Uri("http://localhost/SilverlightApplication2.Web/SilverlightApplication2TestPage.aspx", UriKind.Absolute));
mutex.WaitOne();
Dispatcher.BeginInvoke(() => MessageBox.Show(result));
}
It almost seems like there is an issue with the UI thread that causes the callback to not be executed.
Here is the answer: http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx
You cannot block the UI thread in silverlight.