c# - 从 Task.Run() 冒泡异常
问题描述
我有下面的代码,我试图找出来自 testFunction() 的异常。当我尝试运行代码时,没有抛出异常。
testFunction 是我想定期调用的任务
但是,如果我明确添加 throw new CustomException(); 在 Task.Run 中,代码正确抛出。我无法理解这种行为。我不能等待或等待 Task.Run 因为我希望 task.Run 自己独立运行,因此我使用 ContinueWith 但 continueWith 没有捕获异常,因此不会抛出它。请告知我在这里缺少什么?
public class Example
{
public static CancellationTokenSource source = new CancellationTokenSource();
public static void Main()
{
Console.WriteLine("Hello start");
Task.Run(async () =>
{
while(token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
await testFunction(source.Token);
await Task.Delay(1000,token);
}
} ).ContinueWith((t) =>
{
if (t.Exception != null) throw t.Exception;
});
}
public static async Task testFunction(CancellationToken token)
{
throw new CustomException();
}
}
解决方案
我不能等待或等待 Task.Run 因为我希望 task.Run 自己独立运行
您必须使用await
来观察异常。不过,您不必立即使用await
。如果需要,您可以将其保存Task
在变量中,await
稍后再保存。
因此我正在使用 ContinueWith
ContinueWith
不会做任何async
/await
不能做的事情。ContinueWith
不会帮你的。它实际上应该几乎从不使用。
我正在尝试消除来自 testFunction() 的异常。
让我转过头来:异常在哪里?它在哪里冒泡?代码的哪一部分将观察到该异常?一旦你回答了这个问题,你就会找到把你的await
.
推荐阅读
- php - Keycloak 发送电子邮件重置密码 401 Unauthorized 或 500 Internal Server Error
- python - 如何将当前秒数重新启动到 59 并开始倒计时
- pandas - 根据条件更改数据框行中的值
- ios - 固定的avfoundation变量,不同的显示亮度
- scala - 使用 akka http,如何将请求标头注入服务器中的传入路由?
- microsoft-teams - Action.Submit 不触发服务器中的事件/动作
- javascript - 如何在 ReactJS 中动态导入和渲染组件
- npm - 模块是无关的 npm
- fix-protocol - 在 MULTIPLECHARVALUE 或 MULTIPLESTRINGVALUE 字段中重复相同的值是否合法?
- tableau-api - 根据设置输入输出值对条形图进行排序