IAsyncEnumerable의 취소 토큰 | Code Maze

IAsyncEnumerable의 동작 취소는 좀 다른 방법을 사용합니다.

public static async Task IndefinitelyRunningWrappedMethodCancelled()
{
    var cancellationTokenSource = new CancellationTokenSource();
    cancellationTokenSource.CancelAfter(7000);
    var indefinitelyRunningRange = GetIndefinitelyRunningRangeWrapperAsync();
    await foreach (int index in indefinitelyRunningRange.WithCancellation(cancellationTokenSource.Token))
    {
        // Do something with the index
    }
}
private static async IAsyncEnumerable<int> GetIndefinitelyRunningRangeAsync(
    [EnumeratorCancellation] System.Threading.CancellationToken cancellationToken = default)
{
    int index = 0;
    while (true)
    {
        await Task.Delay(5000, cancellationToken);
        yield return index++;
    }
}
1개의 좋아요