当我通过调用以下内容取消异步方法时Cancel()
我的方法CancellationTokenSource
,最终会停止。然而自从该行Console.WriteLine(await reader.ReadLineAsync());
需要相当多的时间才能完成,我试图通过我的CancellationToken
to ReadLineAsync()
以及(期望它返回一个空字符串),以便使该方法对我的响应更加敏感Cancel()
称呼。然而我无法通过CancellationToken
to ReadLineAsync()
.
我可以取消呼叫吗Console.WriteLine()
or Streamreader.ReadLineAsync()
如果是这样,我该怎么做?
Why is ReadLineAsync()
不接受CancellationToken
?我认为为异步方法提供一个可选选项是一个很好的做法CancellationToken
即使该方法在取消后仍然完成,也可以使用参数。
StreamReader reader = new StreamReader(dataStream);
while (!reader.EndOfStream)
{
if (ct.IsCancellationRequested){
ct.ThrowIfCancellationRequested();
break;
}
else
{
Console.WriteLine(await reader.ReadLineAsync());
}
}
Update:
正如下面评论中所述,Console.WriteLine()
由于每行 40.000 个字符的输入字符串格式不正确,仅调用就已经占用了几秒钟的时间。打破这一点可以解决我的响应时间问题,但我仍然对有关如何取消此长时间运行的语句的任何建议或解决方法感兴趣,如果出于某种原因打算将 40.000 个字符写入一行(例如,将整个字符串转储到一份文件)。
.NET 6 带来任务.WaitAsync(CancellationToken) https://github.com/dotnet/runtime/pull/48842。所以我们可以这样写:
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/20824 https://github.com/dotnet/runtime/issues/20824 and https://github.com/dotnet/runtime/pull/61898 https://github.com/dotnet/runtime/pull/61898.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)