Can i cancel StreamReader.ReadLineAsync with a CancellationToken?

前端 未结 4 1513
北荒
北荒 2020-12-16 12:02

When I cancel my async method with the following content by calling the Cancel() method of my CancellationTokenSource, it will stop eventually. How

4条回答
  •  無奈伤痛
    2020-12-16 12:51

    I like to use an infinite delay, the code is quite clean. If waiting is complete WhenAny returns and the cancellationToken will throw. Else, the result of task will be returned.

    public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
    {
            using (var delayCTS = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                var waiting = Task.Delay(-1, delayCTS.Token);
                var doing = task;
                await Task.WhenAny(waiting, doing);
                delayCTS.Cancel();
                cancellationToken.ThrowIfCancellationRequested();
                return await doing;
            }
    }
    

提交回复
热议问题