迭代时如何跳出 IAsyncEnumerable?
How to break out of an IAsyncEnumerable when iterating?
C# 8 添加了对异步迭代器块的支持,因此您可以等待事物和 return IAsyncEnumarator
而不是 IEnumerable
:
public async IAsyncEnumerable<int> EnumerateAsync() {
for (int i = 0; i < 10; i++) {
yield return i;
await Task.Delay(1000);
}
}
使用 非阻塞 消费代码,如下所示:
await foreach (var item in EnumerateAsync()) {
Console.WriteLine(item);
}
这将导致我的代码 运行 持续大约 10 秒。但是,有时我想在所有元素都被消耗之前打破 await foreach
。但是,对于 break
,我们需要等到当前等待的 Task.Delay
完成。 我们如何才能在不等待任何悬空的异步任务的情况下立即跳出该循环?
使用 CancellationToken
是解决方案,因为这是唯一可以取消代码中的 Task.Delay
的方法。我们在您的 IAsyncEnumerable
中获取它的方式是在创建它时将其作为参数传递,所以让我们这样做:
public async IAsyncEnumerable<int> EnumerateAsync(CancellationToken cancellationToken = default) {
for (int i = 0; i < 10; i++) {
yield return i;
await Task.Delay(1000, cancellationToken);
}
}
消耗方为:
// In this example the cancellation token will be caneled after 2.5 seconds
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2.5));
await foreach (var item in EnumerateAsync(cts.Token)) {
Console.WriteLine(item);
}
当然,这将在返回 3 个元素后取消枚举,但会以从 Task.Delay
中抛出的 TaskCanceledException
结束。要优雅地退出 await foreach
我们必须抓住它并在生产端中断:
public async IAsyncEnumerable<int> EnumerateAsync(CancellationToken cancellationToken = default) {
for (int i = 0; i < 10; i++) {
yield return i;
try {
await Task.Delay(1000, cancellationToken);
} catch (TaskCanceledException) {
yield break;
}
}
}
备注
截至目前,这仍处于预览阶段,可能会发生变化。如果您对此主题感兴趣,您可以在 IAsyncEnumeration
.
中 watch a discussion of the C# language team 关于 CancellationToken
C# 8 添加了对异步迭代器块的支持,因此您可以等待事物和 return IAsyncEnumarator
而不是 IEnumerable
:
public async IAsyncEnumerable<int> EnumerateAsync() {
for (int i = 0; i < 10; i++) {
yield return i;
await Task.Delay(1000);
}
}
使用 非阻塞 消费代码,如下所示:
await foreach (var item in EnumerateAsync()) {
Console.WriteLine(item);
}
这将导致我的代码 运行 持续大约 10 秒。但是,有时我想在所有元素都被消耗之前打破 await foreach
。但是,对于 break
,我们需要等到当前等待的 Task.Delay
完成。 我们如何才能在不等待任何悬空的异步任务的情况下立即跳出该循环?
使用 CancellationToken
是解决方案,因为这是唯一可以取消代码中的 Task.Delay
的方法。我们在您的 IAsyncEnumerable
中获取它的方式是在创建它时将其作为参数传递,所以让我们这样做:
public async IAsyncEnumerable<int> EnumerateAsync(CancellationToken cancellationToken = default) {
for (int i = 0; i < 10; i++) {
yield return i;
await Task.Delay(1000, cancellationToken);
}
}
消耗方为:
// In this example the cancellation token will be caneled after 2.5 seconds
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2.5));
await foreach (var item in EnumerateAsync(cts.Token)) {
Console.WriteLine(item);
}
当然,这将在返回 3 个元素后取消枚举,但会以从 Task.Delay
中抛出的 TaskCanceledException
结束。要优雅地退出 await foreach
我们必须抓住它并在生产端中断:
public async IAsyncEnumerable<int> EnumerateAsync(CancellationToken cancellationToken = default) {
for (int i = 0; i < 10; i++) {
yield return i;
try {
await Task.Delay(1000, cancellationToken);
} catch (TaskCanceledException) {
yield break;
}
}
}
备注
截至目前,这仍处于预览阶段,可能会发生变化。如果您对此主题感兴趣,您可以在 IAsyncEnumeration
.
CancellationToken