Getting “The connection does not support MultipleActiveResultSets” in a ForEach with async-await

前端 未结 4 1219
遥遥无期
遥遥无期 2021-01-03 21:42

I have the following code using Dapper.SimpleCRUD :

var test = new FallEnvironmentalCondition[] {
    new FallEnvironmentalCondition {Id=40,FallId=3,Environm         


        
4条回答
  •  别那么骄傲
    2021-01-03 22:40

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

    Which is equivalent to

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

    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
        }
    

提交回复
热议问题