2

I have a simple program:

class Program
{   
    static void Main(string[] args)
    {
        Run().Wait();
    }

    private static async Task Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

Run() method is intentionally designed to throw NullReferenceException. What bothers me is why exception is thrown on the line

Run.Wait()

instead of on

someVariable.Replace(",",".");

The actuall exception is available in InnerException - why is that? I lose debugging context, because exception is thrown outside of Run method. enter image description here

If my program is synchronous:

class Program
{
    static void Main(string[] args)
    {
        Run();
    }

    private static void Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

exception is thrown on the correct line. Why async breaks this?

Loreno
  • 668
  • 8
  • 26

2 Answers2

5

When you call Run.Wait(), the Run() method has thrown a null exception then Wait method will throw AggregateException. Btw you don't loss your context. If you click on [View Details] and view the StackTrace of InnerException of the current exception, you can found that the exception came from Run() method:

enter image description here

Nhan Phan
  • 1,262
  • 1
  • 14
  • 32
  • When I said about losing context, I meant that I cannot check content of local variables of Run method when exception throws. – Loreno Aug 21 '18 at 10:48
3

What @Nhan Phan is saying is true.

There's also another way you can deal with this issue: Instead of using .Wait() you can use .GetAwaiter.GetResult() which will also unwrap the AggregateException.

If you are using C# 7.1 can have an async void Main and the await your Run method

Igor Meszaros
  • 2,081
  • 2
  • 22
  • 46