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

前端 未结 4 1263
遥遥无期
遥遥无期 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

    MARS has some limitations and also a non-zero overhead. You can use the following helpers to make the updates sequential:

    public static async Task WhenAllOneByOne(this IEnumerable source, Func process)
    {
        foreach (var item in source)
            await process(item);
    }
    
    public static async Task> WhenAllOneByOne(this IEnumerable source, Func> transform)
    {
        var results = new List();
    
        foreach (var item in source)
            results.Add(await transform(item));
    
        return results;
        // I would use yield return but unfortunately it is not supported in async methods
    }
    

    So your example would turn into

    await test.WhenAllOneByOne(conn.UpdateAsync);
    

    I usually call the second helper instead of Task.WhenAll, as follows:

    await Task.WhenAll(source.Select(transform)); // not MARS-safe
    await source.WhenAllOneByOne(transform); // MARS-safe
    

提交回复
热议问题