小编Adr*_*man的帖子

在 Linq 表达式中使用 Async/Await 不会引发异常

晚上,

谁能指出我为什么使用 async 和 await 运算符的 linq 语句不会在堆栈上传播异常但 foreach 循环会传播的文档?必须有一些隐藏的东西并在某处记录了这种行为,我只是没有运气找到它。#googlefoofail #doyouevenasyncbrah

如果您运行单元测试,您将看到它返回时没有错误且有效。但是,如果您调试单元测试,它会因错误而中断,但是它将允许您继续,并且该错误永远不会传播回堆栈。

如果您注释掉 linq 语句并取消注释 foreach 循环,那么在尝试向字典添加重复键时会出现预期的错误。

[TestMethod]
public void tester()
{
    List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>() 
    { 
        { new KeyValuePair<string, string>("test", "first") }, 
        { new KeyValuePair<string, string>("test", "second") } 
    };
    fails = new Dictionary<string, string>();

    pairs.ForEach(async x => await testasync(x));                //<========= does not throw error

    //foreach (KeyValuePair<string,string> pair in pairs)        //<========= throws error
    //{
    //    testasync(pair).GetAwaiter().GetResult();
    //}

    Assert.IsTrue(1 == 1);
}

private Dictionary<string, string> fails;
private async …
Run Code Online (Sandbox Code Playgroud)

c# linq exception async-await

1
推荐指数
1
解决办法
67
查看次数

标签 统计

async-await ×1

c# ×1

exception ×1

linq ×1