.net core uses asynchronous await (Async-await) to prompt "Connection does not support MultipleActiveResultSets" in Foreach

question:

When using the ForEach method of the array collection to perform asynchronous ( Async ) batch update operation entity objects in Lambda , the update fails and an error is thrown: " The connection does not support MultipleActiveResultSets " error message.

 code segment:

demand.Characters.ForEach(async type =>
 {
     var userCharacterDemand = new UserCharacterDemandEntity
     {
        Character = type,
        User = user
     };
     await Context.UserCharacterDemands.AddAsync(userCharacterDemand);
 });

The code starts a task for each item in the list, but doesn't wait for each task to complete before starting the next one.

This is equivalent to:

foreach (var type in demand.Characters)
{
    var userCharacterDemand = new UserCharacterDemandEntity
    {
        Character = type,
        User = user
    };
    Context.UserCharacterDemands.Add(userCharacterDemand);
}

 

reason:

ForEach is not an async method. It will not wait for the Task returned by the Lambda. Executing the ForEach loop will trigger each task and not wait for any tasks to complete.

Key points of the question:

Marking a Lambda as Async does not make the synchronous method you pass it asynchronous.

Solution 1: (recommended)

You need to use a foreach loop to wait for the task to complete.

For example:

foreach(var x in xy) await f(x);

foreach (var type in demand.Characters)
{
    var userCharacterDemand = new UserCharacterDemandEntity
    {
        Character = type,
        User = user
    };
    await Context.UserCharacterDemands.AddAsync(userCharacterDemand);
}

Solution two:

The property MultipleActiveResultSets needs to be added and set to true in the connection string to allow multiple active result sets.

Check the official instructions for details:

Enabling Multiple Active Result Sets - ADO.NET | Microsoft Docs

 

Guess you like

Origin blog.csdn.net/LZD_jay/article/details/125549288