如何链接独立的 C# 任务? [英] How to chain independent C# tasks?
问题描述
假设我有两个独立的异步函数(我无法控制)来创建 Task 对象:
Let's say I have two independent async functions (that I don't control) that create Task objects:
Task A();
Task B();
和其他一些非异步函数
void X();
如何构建一个单独的 Task 链来依次执行所有这些任务并允许附加更多的延续(将在 X 之后执行)?
How do I construct a single Task chain that executes all of these in sequence and allows further continuations (that will execute after X) to be appended?
如果我这样做:
Task Sequential()
{
return A()
.ContinueWith(t => { B(); })
.ContinueWith(t => { X(); });
}
这不起作用,因为 B 将启动一个新的任务链.如果 B 需要很长时间才能完成,X 将首先执行(以及 Sequential 的调用者可能在返回的任务上继续执行的其他任何内容).我需要 X 作为单个任务链中的最后一个元素,并以 B 任务作为其先例.
that does not work, because B will start a new Task chain. If B takes a long time to complete, X will be executed first (along with whatever else the caller of Sequential might ContinueWith on the returned Task). I need X to be the last element in a single Task chain, with the B Task as its precedent.
如果我这样做:
Task Sequential()
{
return A()
.ContinueWith(t => { B().ContinueWith(t => { X(); }); });
}
这只能部分解决问题,因为即使 A、B 和 X 现在按顺序执行,如果调用者执行 Sequential().ContinueWith,则该继续将与 B 和 X 并行执行,而不是在 X 之后执行.
that only partially solves the problem, because even though A, B and X will now execute in sequential order, if the caller does Sequential().ContinueWith, that continuation will execute in parallel to B and X, not after X.
推荐答案
有什么理由不使用 await?例如,
Is there any reason not to use await? For example,
async Task Sequential()
{
await A();
await B();
X();
}
这篇关于如何链接独立的 C# 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!