得到“该连接不支持MultipleActiveResultSets".在带有async-await的ForEach中 [英] Getting "The connection does not support MultipleActiveResultSets" in a ForEach with async-await

查看:792
本文介绍了得到“该连接不支持MultipleActiveResultSets".在带有async-await的ForEach中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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
    }

这篇关于得到“该连接不支持MultipleActiveResultSets".在带有async-await的ForEach中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆