gpt4 book ai didi

c# - 我可以使用 CancellationToken 取消 StreamReader.ReadLineAsync 吗?

转载 作者:行者123 更新时间:2023-12-03 03:34:23 25 4
gpt4 key购买 nike

当我通过调用 CancellationTokenSourceCancel() 方法取消具有以下内容的异步方法时,它最终会停止。然而,由于 Console.WriteLine(await reader.ReadLineAsync()); 行需要相当多的时间才能完成,我尝试将我的 CancellationToken 传递给 ReadLineAsync() 以及(期望它返回一个空字符串),以使该方法对我的 Cancel() 调用更加敏感。但是我无法将 CancellationToken 传递给 ReadLineAsync()

我可以取消对 Console.WriteLine()Streamreader.ReadLineAsync() 的调用吗?如果可以,我该怎么做?

为什么ReadLineAsync()不接受CancellationToken?我认为为异步方法提供可选的 CancellationToken 参数是一个很好的做法,即使该方法在取消后仍然完成。

StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{
if (ct.IsCancellationRequested){
ct.ThrowIfCancellationRequested();
break;
}
else
{
Console.WriteLine(await reader.ReadLineAsync());
}
}

更新:正如下面的评论中所述,由于每行 40.000 个字符的输入字符串格式不正确,仅 Console.WriteLine() 调用就已经占用了几秒钟的时间。打破这一点可以解决我的响应时间问题,但我仍然对有关如何取消此长时间运行的语句的任何建议或解决方法感兴趣,如果出于某种原因打算将 40.000 个字符写入一行(例如,将整个字符串转储到一个文件)。

最佳答案

.NET 6 带来 Task.WaitAsync(CancellationToken) 。所以可以这样写:

using StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{
Console.WriteLine(await reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false));
}

在.NET 7(尚未发布)中,应该可以简单地编写:

using StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{
Console.WriteLine(await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
}

基于https://github.com/dotnet/runtime/issues/20824https://github.com/dotnet/runtime/pull/61898 .

关于c# - 我可以使用 CancellationToken 取消 StreamReader.ReadLineAsync 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com