以下是 Microsoft在 ASP.NET Core SignalR中使用流式传输一文的摘录:
private async Task WriteItemsAsync(
ChannelWriter<int> writer,
int count,
int delay,
CancellationToken cancellationToken)
{
try
{
for (var i = 0; i < count; i++)
{
// Check the cancellation token regularly so that the server will stop
// producing items if the client disconnects.
cancellationToken.ThrowIfCancellationRequested();
await writer.WriteAsync(i);
// Use the cancellationToken in other APIs that accept cancellation
// tokens so the cancellation can flow down to them.
await Task.Delay(delay, cancellationToken);
}
}
catch (Exception ex)
{
writer.TryComplete(ex);
}
writer.TryComplete();
}
如果有异常,它会先调用 writer.TryComplete(ex),然后调用 writer.TryComplete()。换句话说,它两次调用 TryComplete(尽管重载不同)。
这是必要的吗?我应该在 writer.TryComplete(ex) 之后添加一个 return 语句以避免调用它两次吗?或者第二个 writer.TryComplete() 在调用前者之后是否有一些有意义的目的?