Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

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?)

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);
}

Open in new window

Avatar of ste5an
ste5an
Flag of Germany image

Normally there is only one UI thread. I'm not sure, but I guess your message box call runs on that. So imho you're blocking the main thread, not (dead) locking it.

The question is, why do you want an async message box?
Avatar of deleyd

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.)
Avatar of deleyd

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
Avatar of deleyd
deleyd
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial