TPL TaskScheduler 一次只能看到一个异步方法的一个同步段,因此您不能简单地使用调度程序来做到这一点。但是您可以使用更高级别的原语来做到这一点。我经常使用的一种是 TPL 数据流。
首先,安装 NuGet 包:
Install-Package Microsoft.Tpl.Dataflow
然后使用此代码:
private static async Task doThing(object i) {
Console.WriteLine("in do thing {0}", (int)i);
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("out of do thing {0}", (int)i);
}
static void Main(string[] args) {
CancellationTokenSource source = new CancellationTokenSource();
var exclusivityBlock = new ActionBlock<Func<Task>>(f => f(), new ExecutionDataflowBlockOptions { CancellationToken = source.Token }};
exclusivityBlock.Post(() => doThing(1));
exclusivityBlock.Post(() => doThing(2));
exclusivityBlock.Post(() => doThing(3));
exclusivityBlock.Post(
async () => {
Console.WriteLine("in do thing {0}", 4);
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("out of do thing {0}", 4);
});
exclusivityBlock.Complete();
exclusivityBlock.Completion.Wait();
Console.WriteLine("Done");
Console.ReadKey();
return;
}
此代码缺少每个已发布工作项的单独任务。如果这很重要,您可以使用此示例:
internal static class Program {
private static async Task doThing(object i) {
Console.WriteLine("in do thing {0}", (int)i);
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("out of do thing {0}", (int)i);
}
private static void Main(string[] args) {
CancellationTokenSource source = new CancellationTokenSource();
var exclusivityBlock = CreateTrackingBlock<Func<Task>>(
f => f(), new ExecutionDataflowBlockOptions { CancellationToken = source.Token });
var task1 = exclusivityBlock.PostWithCompletion(() => doThing(1));
var task2 = exclusivityBlock.PostWithCompletion(() => doThing(2));
var task3 = exclusivityBlock.PostWithCompletion(() => doThing(3));
var task4 = exclusivityBlock.PostWithCompletion(
async () => {
Console.WriteLine("in do thing {0}", 4);
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("out of do thing {0}", 4);
});
Task.WaitAll(task1, task2, task3, task4);
Console.WriteLine("Done");
Console.ReadKey();
return;
}
private static ActionBlock<Tuple<T, TaskCompletionSource<object>>> CreateTrackingBlock<T>(Func<T, Task> action, ExecutionDataflowBlockOptions options = null) {
return new ActionBlock<Tuple<T, TaskCompletionSource<object>>>(
async tuple => {
try {
await action(tuple.Item1);
tuple.Item2.TrySetResult(null);
} catch (Exception ex) {
tuple.Item2.TrySetException(ex);
}
},
options ?? new ExecutionDataflowBlockOptions());
}
internal static Task PostWithCompletion<T>(this ActionBlock<Tuple<T, TaskCompletionSource<object>>> block, T value) {
var tcs = new TaskCompletionSource<object>();
var tuple = Tuple.Create(value, tcs);
block.Post(tuple);
return tcs.Task;
}
}
但是请注意,这只是有点费力,因为 Dataflow 主要不是为跟踪单个提交而设计的,而是为跟踪整个过程而设计的。因此,虽然上述工作正常,但斯蒂芬克利里的答案可能更简单,因此更可取。