【发布时间】:2021-07-18 02:28:31
【问题描述】:
晚上,
谁能指出我为什么使用 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 Task testasync(KeyValuePair<string, string> pair)
{
fails.Add(pair.Key, pair.Value);
}
【问题讨论】:
-
不确定文档,但是这里提到了一个扩展方法stackoverflow.com/a/28996883/4149124,它可以帮助你抛出异常。
标签: c# linq exception async-await