处理来自非等待任务的异常 [英] Handling exception from non-awaited Task

查看:32
本文介绍了处理来自非等待任务的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有 Main 方法的控制台应用程序,如下所示:

Let's assume I have a console application with Main method, something like this:

public static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
    {
        Console.WriteLine("App Unobserved");
    };
    TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
    {
        Console.WriteLine("Task Unobserved");
    };
    Task.Run(async () => await MyAwesomeMethod());
    // other awesome code...
    Console.ReadLine();
}

public static async Task MyAwesomeMethod()
{
    // some useful work
    if (something_went_wrong)
        throw new Exception();
    // other some useful work
}

所以,我只是运行 MyAwesomeMethod(即发即弃),并想做一些其他工作,但我也想知道是否有任何未处理的异常.但是应用程序成功完成,没有任何问题(异常被吞下).

So, I just run MyAwesomeMethod (fire-and-forget), and want to do some other job, but I also want to know if there any unhandled exceptions. But application finishes successfully without any sign of problem (exception is just swallowed).

如何在不等待或不使用 Task.Run(...).Wait() 的情况下处理来自 MyAwesomeMethod() 的异常?

How can I handle exception from MyAwesomeMethod(), without awaiting it or using Task.Run(...).Wait()?

推荐答案

所以,我只运行 MyAwesomeMethod(即发即弃)...但我也想知道是否有任何未处理的异常.但是应用程序成功完成,没有任何问题(异常被吞下).

So, I just run MyAwesomeMethod (fire-and-forget)... but I also want to know if there any unhandled exceptions. But application finishes successfully without any sign of problem (exception is just swallowed).

那不是即发即忘".一劳永逸"字面意思是你不在乎任务何时(或是否)完成(或错误).

That's not "fire and forget", then. "Fire and forget" literally means that you don't care when (or whether) the task completes (or errors).

如何在不等待或不使用 Task.Run(...).Wait() 的情况下处理来自 MyAwesomeMethod() 的异常?

How can I handle exception from MyAwesomeMethod(), without awaiting it or using Task.Run(...).Wait()?

无论如何都要使用await:

Task.Run(async () => {
  try {
    await MyAwesomeMethod();
  } catch (Exception ex) {
    Console.WriteLine(ex);
  }
});

这篇关于处理来自非等待任务的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆