deleyd
asked on
Why does this code deadlock?
Why does this code deadlock?
I created a simple WPF project with a single button, and this is the button click code.
If I comment out the SetSynchronizationContext then it works. (Which brings up another question, why doesn't it crash complaining I'm not on a STA thread for the second MessageBox, because after the await it resumes on a different thread.)
With the SetSynchronizationContext line, it seems to deadlock at the await statement, I'm guessing it's unable to resume on the same thread it started on. Is there a hidden .Join() or .Wait() somewhere blocking the thread it started on? Is the thread it started on blocked somehow? (Or is it gone?)
I created a simple WPF project with a single button, and this is the button click code.
If I comment out the SetSynchronizationContext then it works. (Which brings up another question, why doesn't it crash complaining I'm not on a STA thread for the second MessageBox, because after the await it resumes on a different thread.)
With the SetSynchronizationContext line, it seems to deadlock at the await statement, I'm guessing it's unable to resume on the same thread it started on. Is there a hidden .Join() or .Wait() somewhere blocking the thread it started on? Is the thread it started on blocked somehow? (Or is it gone?)
private void Button_Click(object sender, RoutedEventArgs e)
{
// Create a thread
Thread newWindowThread = new Thread(new ThreadStart(async () =>
{
MessageBox.Show("Initial ThreadId=" + Thread.CurrentThread.ManagedThreadId.ToString());
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
await DoAsync();
MessageBox.Show("Now ThreadId2=" + Thread.CurrentThread.ManagedThreadId.ToString());
}));
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
}
private async Task DoAsync()
{
await Task.Delay(1000);
}
ASKER
It's a mockup of a quick kludge fix I'm testing.
The correct fix of course would be to rewrite the code to use the UI thread when it wants to display a window.
Now it's just academic interest to understand what's going on. It displays the first message box, but never the second. (Good idea it might be the message box. The actual code creates a dialog window.)
The correct fix of course would be to rewrite the code to use the UI thread when it wants to display a window.
Now it's just academic interest to understand what's going on. It displays the first message box, but never the second. (Good idea it might be the message box. The actual code creates a dialog window.)
ASKER
It appears the thread is terminated when it comes to the await? Does a thread terminate when the code it's running returns?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The question is, why do you want an async message box?