我有以下方法从 http 流中读取 csv 文档
public async IAsyncEnumerable<Line> GetLines([EnumeratorCancellation] CancellationToken cancellationToken)
{
HttpResponseMessage response = GetResponse();
using var responseStream = await response.Content.ReadAsStreamAsync();
using var streamReader = new StreamReader(responseStream);
using var csvReader = new CsvReader(streamReader);
while (!cancellationToken.IsCancellationRequested && await csvReader.ReadAsync())
{
yield return csvReader.GetRecord<Line>();
}
}
以及使用结果的其他方法
var documentAsyncEnumerable = graphClient.GetLines(cancellationToken);
await foreach (var document in documentAsyncEnumerable.WithCancellation(cancellationToken))
{
// Do something with document
}
我的问题是我应该只在一个地方使用取消令牌吗?是否应该在产生记录之前对取消令牌采取行动,还是 IAsyncEnumerable.WithCancellation() 基本上做同样的事情?如果有,有什么区别?