0

I'm trying to learn about async and await in C#, and have been reading MSDN. I arrived at this example which I've copied into a console app in the hope of using the debugger to see how exceptions are handled asynchronously.

Using the info in this answer, I adapted the MS code to run it in the app (perhaps wrongly as a learner). The error message I get is on this line:

Task<string> theTask = DelayAsync();

CS0120 An object reference is required for the non-static field, method, or property 'Program.DelayAsync()'

Is this something I've done wrong, or a bug in the MSDN code? Can anyone please explain how to run the DoSomethingAsync() method from a console app so that I can see in the debugger how the exception is returned please?

class Program
{
    static void Main()
    {
        DoSomethingAsync().Wait();
    }

    static async Task DoSomethingAsync()
    {
        Task<string> theTask = DelayAsync();
        try
        {
            string result = await theTask;
            Debug.WriteLine("Result: " + result);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Exception Message: " + ex.Message);
        }
        Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);
        Debug.WriteLine("Task IsFaulted:  " + theTask.IsFaulted);
        if (theTask.Exception != null)
        {
            Debug.WriteLine("Task Exception Message: " + theTask.Exception.Message);
            Debug.WriteLine("Task Inner Exception Message: " + theTask.Exception.InnerException.Message);
        }
    }

    private async Task<string> DelayAsync()
    {
        await Task.Delay(100);
        //throw new OperationCanceledException("canceled");
        //throw new Exception("Something happened.");
        return "Done";
    }
}
Community
  • 1
  • 1
EvilDr
  • 8,943
  • 14
  • 73
  • 133
  • You are calling from a static method, the called method should be static or you need to create an instance of the class Program and call through that instance. Find more info in the duplicate – Steve Mar 30 '16 at 11:37
  • With respect, the question doesn't provide an easy answer for someone learning C# or async, given that async was introduced in VS2012 and the question was asked in 2009. Although the error is the same, the cause is somewhat different. However, your accompanying advice *does* provide enough to go on, so thank you. – EvilDr Mar 30 '16 at 12:43
  • `static void Main()` changed to an async button click event handler in a Windows form, which works fine. – EvilDr Mar 30 '16 at 13:14

0 Answers0