MessageDialog task not shown if i use Task.Wait() instead of await
Asked Answered
C

2

2

I don't know the difference beetween await a task and use task.Wait() but for the MessageDialog.ShowAsync method with the first it works but not with the second (while the two syntax works with other async methods).

If anyone could explain why i will be interested !

// this don't work, no dialog is shown (and UI is block)
var dialog = new MessageDialog("fail");
var task = dialog.ShowAsync().AsTask();
task.Wait();

// this work
var dialog = new MessageDialog("success");
var task = dialog.ShowAsync().AsTask();
await task;

You will ask me why i want to do this, it's because i need to show a dialog in a catch block (to show an error message) and wait for the user to close the dialog before continue after the catch block (and yes we can't use await in a catch block but we can use Task.Wait(), i've used it successfully with other async methods).

Croissant answered 24/6, 2012 at 15:41 Comment(0)
F
2

Showing the dialog (and responding to button click in it) has to be done from the UI thread. But if you call Wait() on the UI thread, you're basically saying that nothing else can happen on that thread, until that Task completes. That's why the dialog can't be shown and that's also why your application freezes.

So, the UI thread is waiting for the dialog, but the dialog is waiting for the UI thread, which is a classical deadlock. I believe using Wait() on the UI thread is the most common cause of deadlocks in C# 5 GUI applications.

Farly answered 24/6, 2012 at 16:16 Comment(4)
Great observation - given the effect of killing the ability to process further messages, I wonder if Wait() being called on the UI thread is something that could be detected and cause a throw (much like trying to write to UI components from the wrong thread does) to improve the developer experience (since 'frozen app' is not a very actionable/debuggable state :)Catabolism
Way too late for 2012, of course, but filed it anyway - connect.microsoft.com/VisualStudio/feedback/details/750636/…Catabolism
@JamesManning I don't think that would be a good idea. Wait()ing on something that doesn't use the UI thread is perfectly valid approach (although maybe not very user-friendly, because of the temporary freezing), especially in C# 4 code.Farly
sorry for not clarifying - Wait()ing from the UI thread when the task you're waiting on has the synchronization context the says it has to run on the UI thread. Of course, it could (and might, I forget) just run the task in such a scenario.Catabolism
W
1

task.Wait() blocks until the task is complete, while await continues processing. My guess is that because the UI is blocked, the message dialog cannot appear.

Winchell answered 24/6, 2012 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.