如果我使用Task.Wait(而不是等待MessageDialog任务未显示) [英] MessageDialog task not shown if i use Task.Wait() instead of await

查看:208
本文介绍了如果我使用Task.Wait(而不是等待MessageDialog任务未显示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知的差beetween等待一个任务,并使用task.Wait(),但该方法MessageDialog.ShowAsync与第一它的工作原理,但不与第二个(而两个语法可与其它异步方法)。

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;

您会问我,为什么我想这样做,是因为我需要显示在一个catch块一个对话框(显示错误消息),并等待用户之前关闭对话框catch块后继续(与是的,我们不能用计谋在catch块,但我们可以用Task.Wait(),我用它成功地与其他异步方法)。

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

推荐答案

显示对话框(和响应按钮点击的话)必须从用户界面线程中完成的。但是,如果你调用等待()在UI线程上,你基本上说,没有别的可以在该线程发生,直到工作完成。这就是为什么不能显示的对话框,这也是为什么你的应用程序冻结。

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.

所以,UI线程正在等待的对话框,但是对话正在等待UI线程,这是一种典型的僵局。我相信,使用等待()在UI线程死锁是在C#中5 GUI应用程序的最常见原因。

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.

这篇关于如果我使用Task.Wait(而不是等待MessageDialog任务未显示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆