Search code examples
c#.netexceptiontask-parallel-libraryunobserved-exception

Handling exception from non-awaited Task


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
}

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).

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


Solution

  • 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).

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

    Use await anyway:

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