在ContinueWith()块中使用await [英] Using await inside a ContinueWith() block
问题描述
我有以下代码:
var result = MessageBoxHelper.MsgBox
.ShowAsync("Press Yes to proceed", MessageBoxButton.YesNo)
.ContinueWith((answer) =>
{
if (answer.Result == MessageBoxResult.Yes)
{
Task<bool> asyncTask = ExecuteAsyncFunc();
//asyncTask.Unwrap(); ??
asyncTask.ContinueWith((a) =>
{
// More
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
在其他地方这样调用:
public async Task<bool> ExecuteAsyncFunc()
{
await CallAnotherAsyncFunction();
}
我相信我需要在试图调用的地方调用Unwrap(),因为我正在ContinueWith()
块内调用await.但是,取消注释时会出现以下错误:
I believe that I need to call Unwrap(), where I have tried to, because I am calling await inside a ContinueWith()
block. However, I get the following error when I uncomment it:
错误CS1929任务"不包含展开"的定义 最好的扩展方法重载 'TaskExtensions.Unwrap(Task)'需要一个类型的接收器 任务"
Error CS1929 'Task' does not contain a definition for 'Unwrap' and the best extension method overload 'TaskExtensions.Unwrap(Task)' requires a receiver of type 'Task'
我是否需要在这种情况下使用Unwrap?如果是,我在做什么错了?
Do I need to use Unwrap in this context, and if so, what am I doing wrong?
推荐答案
简短的答案是使用await
代替ContinueWith
:
The short answer is to use await
instead of ContinueWith
:
var result = MessageBoxHelper.MsgBox.ShowAsync("Press Yes to proceed", MessageBoxButton.YesNo);
if (answer == MessageBoxResult.Yes)
{
var a = await ExecuteAsyncFunc();
// More
}
长答案是 ContinueWith
具有某些危险的默认值选项(包括使用环境TaskScheduler
)和await
自动为您正确执行所有操作.我会在博客上详细介绍.
The long answer is that ContinueWith
has some dangerous default options (including using an ambient TaskScheduler
), and await
automatically does everything correctly for you. I go into more detail on my blog.
这篇关于在ContinueWith()块中使用await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!