Pau*_*els 5 c# asynchronous task task-parallel-library async-await
我有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
在其他地方调用是这样的:
public async Task<bool> ExecuteAsyncFunc()
{
await CallAnotherAsyncFunction();
}
Run Code Online (Sandbox Code Playgroud)
我相信我需要调用 Unwrap(),我已经尝试过,因为我在块内调用 wait ContinueWith()。但是,当我取消注释时,出现以下错误:
错误 CS1929“任务”不包含“展开”的定义,并且最佳扩展方法重载“TaskExtensions.Unwrap(Task)”需要“任务”类型的接收器
我是否需要在这种情况下使用 Unwrap?如果需要,我做错了什么?
简短的答案是使用await而不是ContinueWith:
var result = MessageBoxHelper.MsgBox.ShowAsync("Press Yes to proceed", MessageBoxButton.YesNo);
if (answer == MessageBoxResult.Yes)
{
var a = await ExecuteAsyncFunc();
// More
}
Run Code Online (Sandbox Code Playgroud)
长答案是ContinueWith有一些危险的默认选项(包括使用环境TaskScheduler),并await自动为您正确执行所有操作。我在我的博客上详细介绍了这一点。