我有以下代码:
//Await #1
var response1 = await doSomething();
if(response1.isSuccess) {
//Await #2
var response2 = await doSomethingElse();
}
响应 1 和响应 2 是完全独立的,我想在这里并行化等待任务。 基本上,响应 2 需要花费大量时间,因此仅当响应 1 成功时才会调用。 有什么方法可以调用这两个任务并查看响应 1 的结果,如果失败,我会删除/跳过 Await#2 的响应。
最佳答案
本质上,您想要的是取消任务,但需要更多逻辑。
您需要编辑doSomethingElse
,以便它接受CancellationToken
,并利用它来停止正在执行的操作:
public async Task<Foo> DoSomethingElse(CancellationToken token) {
...
if (token.IsCancellationRequested) {
// stop what you are doing...
// I can't tell you how to implement this without seeing how DoSomethingElse is implemented
}
...
}
现在,从 CancellationTokenSource
获取 CancellationToken
:
var source = new CancellationTokenSource();
var token = source.Token;
这里是“如果响应 1 失败取消响应 2”的逻辑:
var response2Task = DoSomethingElse(token);
var response1 = await DoSomething();
if (!response1.IsSuccess) {
source.Cancel();
} else {
var response2 = await response2Task;
}
关于c# - 跳过等待任务响应条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466823/