测量C#中显示错误时间跨度的多个任务的持续时间

我正在尝试测量完成一组异步任务所需的时间。我的方法是

var stopwatch = Stopwatch.StartNew();
await Task.WhenAll(tasks);
stopwatch.Stop();

我坐着等待操作结束超过5分钟,但秒表将显示1.5秒已过去。

我也尝试过:

var stopwatch = Stopwatch.StartNew();
await Task.WhenAll(tasks).ContinueWith(task => stopwatch.Stop());

...但是这仍然报告仅发生了1.5秒,但仍然需要5分钟才能运行。

tasks is a variable of type IEnumerable<Task<T>>.

我正在努力寻找一种诊断方法,希望能得到一些帮助。谢谢!

更新资料

这是一个更完整的示例:

public async Task<BulkOperationResponse<Source>> BulkInsertSourceDocumentsAsync(IEnumerable<Source> documents)
{
    _logger.LogInformation("Beginning bulk insert...");

    var tasks = new List<Task<OperationResponse<Source>>>(documents.Count());
    tasks.AddRange(documents.Select(document =>
        _orderStatusesContainer.CreateItemAsync(document, new PartitionKey(document.CUSTACCOUNT))
            .CaptureOperationResponse(document)));

    var response = await ExecuteTasksAsync(tasks);

    return response;
}
public async Task<BulkOperationResponse<T>> ExecuteTasksAsync<T>(
    IReadOnlyCollection<Task<OperationResponse<T>>> tasks)
{
    _logger.LogInformation($"Executing {tasks.Count} tasks");

    // TODO: This seems to be reporting the wrong time
    // Opened an issue on GitHub: https://github.com/MicrosoftDocs/azure-docs/issues/53193
    var stopwatch = Stopwatch.StartNew();
    await Task.WhenAll(tasks);
    stopwatch.Stop();

    _logger.LogInformation($"Finished {tasks.Count} tasks in {stopwatch.Elapsed}");

    return new BulkOperationResponse<T>
    {
        TotalTimeTaken = stopwatch.Elapsed, // TODO: Confirm time is correct.
        TotalRequestUnitsConsumed = tasks.Sum(task => task.Result.RequestUnitsConsumed),
        SuccessfulDocuments = tasks.Count(task => task.Result.IsSuccessful),
        Failures = tasks.Where(task => !task.Result.IsSuccessful)
            .Select(task => (task.Result.Item, task.Result.CosmosException)).ToList()
    };
}

在我的测试中,我要导入400,000个文档,并且它们都在5分钟后成功完成。

评论