Can i cancel StreamReader.ReadLineAsync with a CancellationToken?

前端 未结 4 1517
北荒
北荒 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条回答
  •  Happy的楠姐
    2020-12-16 12:54

    You can't cancel Streamreader.ReadLineAsync(). IMHO this is because reading a single line should be very quick. But you can easily prevent the Console.WriteLine() from happening by using a separate task variable.

    The check for ct.IsCancellationRequested is also redundand as ct.ThrowIfCancellationRequested() will only throw if cancellation is requested.

    StreamReader reader = new StreamReader(dataStream);
    while (!reader.EndOfStream)
    {
        ct.ThrowIfCancellationRequested();
        string line = await reader.ReadLineAsync());
    
        ct.ThrowIfCancellationRequested();    
        Console.WriteLine(line);
    }
    

提交回复
热议问题