Handling exception from non-awaited Task

Viewed 1599

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()?

4 Answers
Related