Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async exception handling with void

I'm using Async CTP to write an IO heavy console app. But I'm having problems with exceptions.

public static void Main()
{
   while (true) {
     try{
         myobj.DoSomething(null);
     }
     catch(Exception){}
     Console.Write("done");
     //...
   }
}

//...
public async void DoSomething(string p)
{
   if (p==null) throw new InvalidOperationException();
   else await SomeAsyncMethod();
}

And the following happens: "done" gets written to the console, then I get the exception in the debugger, then I press continue my program exists.
What gives?

like image 453
TDaver Avatar asked Jun 08 '11 19:06

TDaver


People also ask

Can we use async with void?

You use the void return type in asynchronous event handlers, which require a void return type. For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited.

How do you handle async exceptions?

Implement try-catch within the function This is the solution to catch exceptions in asynchronous methods. Have a look at the following code. If you look closely inside the ShowAsync() function, then you will find we have implemented a try-catch within Task. run().

What happens if an exception is thrown within an asynchronous method?

When an exception occurs in an async method that has a return type of Task or Task, the exception object is wrapped in an instance of AggregateException and attached to the Task object. If multiple exceptions are thrown, all of them are stored in the Task object.

Does async await use thread pool?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.


1 Answers

If you give your Console application an async-compatible context (e.g., AsyncContext (docs, source) from my AsyncEx library), then you can catch exceptions that propogate out of that context, even from async void methods:

public static void Main()
{
  try
  {
    AsyncContext.Run(() => myobj.DoSomething(null));
  }
  catch (Exception ex)
  {
    Console.Error.WriteLine(ex.Message);
  }
  Console.Write("done");
}

public async void DoSomething(string p)
{
  if (p==null) throw new InvalidOperationException();
  else await SomeAsyncMethod();
}
like image 180
Stephen Cleary Avatar answered Oct 11 '22 20:10

Stephen Cleary