gpt4 book ai didi

c# - 在 ContinueWith() block 中使用 await

转载 作者:太空狗 更新时间:2023-10-30 00:24:00 25 4
gpt4 key购买 nike

我有以下代码:

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() block 中调用 await。但是,当我取消注释时出现以下错误:

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,如果需要,我做错了什么?

最佳答案

简短的回答是使用 await 而不是 ContinueWith:

var result = MessageBoxHelper.MsgBox.ShowAsync("Press Yes to proceed", MessageBoxButton.YesNo);
if (answer == MessageBoxResult.Yes)
{
var a = await ExecuteAsyncFunc();
// More
}

长答案是 ContinueWith has some dangerous default options (including using an ambient TaskScheduler) ,并且 await 会自动为您正确地完成所有事情。我在我的博客上进行了更详细的介绍。

关于c# - 在 ContinueWith() block 中使用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com