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

查看:91
本文介绍了获取“连接不支持 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.

推荐答案

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

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));
    }

如果您使用的是非异步方法,则必须使用 Wait(),而不是等待每个任务.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天全站免登陆