得到“该连接不支持MultipleActiveResultSets".在带有async-await的ForEach中

得到“该连接不支持MultipleActiveResultSets

问题描述:

我使用Dapper.SimpleCRUD编写以下代码:

I have the following code using Dapper.SimpleCRUD :

var test = new FallEnvironmentalCondition[] {
    new FallEnvironmentalCondition {Id=40,FallId=3,EnvironmentalConditionId=1},
    new FallEnvironmentalCondition {Id=41,FallId=3,EnvironmentalConditionId=2},
    new FallEnvironmentalCondition {Id=42,FallId=3,EnvironmentalConditionId=3}
};
test.ToList().ForEach(async x => await conn.UpdateAsync(x));

使用此代码,我得到以下异常:

With this code, I am getting following exception:

InvalidOperationException:该连接不支持MultipleActiveResultSets

InvalidOperationException: The connection does not support MultipleActiveResultSets

我不知道我正在await每次更新,所以为什么会出现此错误.

I don't understand I am awaiting each update so why am I getting this error.

注意:我无法控制连接字符串,因此无法打开MARS.

Note: I have no control on the connection string so I can't turn MARS on.

该代码为列表中的每个项目启动了一个Task,但是在启动下一个任务之前不等待每个任务完成.在每个任务中,它等待更新完成.试试

That code starts a Task for each item in the list, but does not wait for the each task to complete before starting the next one. Inside each Task it waits for the update to complete. Try

 Enumerable.Range(1, 10).ToList().ForEach(async i => await Task.Delay(1000).ContinueWith(t => Console.WriteLine(DateTime.Now)));

相当于

    foreach (var i in Enumerable.Range(1, 10).ToList() )
    {
        var task = Task.Delay(1000).ContinueWith(t => Console.WriteLine(DateTime.Now));
    }

如果您使用的是非异步方法,则必须等待(而不是等待每个任务). EG

If you're in a non-async method you will have to Wait(), not await each task. EG

    foreach (var i in Enumerable.Range(1, 10).ToList() )
    {
        var task = Task.Delay(1000).ContinueWith(t => Console.WriteLine(DateTime.Now));
        //possibly do other stuff on this thread
        task.Wait(); //wait for this task to complete
    }