Azure / azure-cosmos-dotnet-v3

.NET SDK for Azure Cosmos DB for the core SQL API
MIT License
723 stars 477 forks source link

ReadManyItemsAsync -> ReadManyTaskHelperAsync wraps forked IO task into Task.Run #4527

Open yar-shukan opened 3 weeks ago

yar-shukan commented 3 weeks ago

Describe the bug ReadManyTaskHelperAsync code has suspicious Task.Run call that looks as a potential issue: Task.Run schedules task on thread pool's thread and potentially can cause thread pool being exhausted.

This Task.Run call looks unnecessary and instead of wrapping async code into Task.Run (that can put higher pressure on thread pool) ReadManyTaskHelperAsync -> for loop -> tasks.Add(Task.Run(async () => why code doesn't do this instead: ReadManyTaskHelperAsync -> for loop -> tasks.Add(DoStuffAsync(params, semaphore))

private Task<List<ResponseMessage>> DoStuffAsync(.. otherParams, SemaphoreSlim semaphore)
{
    try
    {
       QueryDefinition queryDefinition = ((this.partitionKeySelectors.Count == 1) && (this.partitionKeySelectors[0] == "[\"id\"]"))
            ? this.CreateReadManyQueryDefinitionForId(entry.Value, indexCopy)
            : this.CreateReadManyQueryDefinitionForOther(entry.Value, indexCopy);

        return await this.GenerateStreamResponsesForPartitionAsync(queryDefinition,
            entry.Key,
            readManyRequestOptions,
            childTrace,
            cancellationToken);
    }
    finally
    {
        semaphore.Release();
        childTrace.Dispose();
    }
}

To Reproduce Run ReadManyTaskHelperAsync

Expected behavior Task.Run is not called in ReadManyItemsAsync execution. Thread pool is not used.

Actual behavior Task.Run is called in ReadManyItemsAsync execution. Thread pool is used.

Environment summary SDK Version: 3.39.1 OS Version: Windows

Additional context There was potential issue reported here but it was not really proven that issue came out of this method call and reporter eventually mitigated with other solution.

cc @ealsur