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";
}
}