简体   繁体   中英

Parallel connection to Microsoft Azure Cosmos DB

I use a library that acts as a repository manager in my code by providing functions to retrieve some information from an Azure Cosmos DB ( _repositoryManager in this case). I want to improve the time performance of the following code that iterates through listOfGroupIds and retrieves them one by one:

foreach(var groupId in listOfGroupIds)
{
    var itemsForGroup = await _repositoryManager.GetItemsByGroupId(groupId);
    itemList.AddRange(itemsForGroup);
}

I am wondering if I am allowed to run them in parallel by:

Parallel.ForEach(listOfGroupIds, groupId =>
{
    var itemsForGroup = _repositoryManager.GetItemsByGroupId(groupId);
    lock (itemList)
        itemList.AddRange(itemsForGroup.Result);
});

by knowing the repository manager uses CosmosClient GetConnection() . My hesitation is I don't know if Microsoft.Azure.Cosmos.CosmosClient() opens a new connection for each query, or if it uses a single connection upon initialization which in the latter case, should I have concerns about the functionality of the code in cases where there are many groupId s and it might open many requests in parallel?

The Cosmos client maintains connections behind the scenes and will reuse connections to your account.

If you are trying to lookup a large group of individual items, the most efficient way is to use ReadManyItemsAsync(), versus using a query or calling ReadItemAsync() in a loop.

You need both the partition key and id. You can learn more about it here, Container.ReadManyItemsAsync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM