2

What is the preferred way to run an async method synchronously?

This is what I currently do:

void RunSync() {
    var task = Task.Run(() => RunAsync());
    task.Wait();
}

async Task RunAsync() {
     throw Exception("test");
}

My problem with the above code is that task.Wait() throws an AggregateException rather than the actual exception thrown by RunAsync which is what I'd prefer.

Is there a way to propagate the actual exception from RunAsync without resorting to catching AggregateException and unwrapping?

svick
  • 236,525
  • 50
  • 385
  • 514
CoderBrien
  • 663
  • 1
  • 7
  • 22

2 Answers2

3

Fast answer:

Change this:

var task = Task.Run(() => RunAsync());
task.Wait();

to this:

var task = RunAsync();
task.Wait();

You should not wrap async methods with Task.Run for running it. Read SO answers 'How to call async methods from sync context', e.g. How would I run an async Task<T> method synchronously?

Community
  • 1
  • 1
mukh1n
  • 158
  • 1
  • 7
  • from your link- is all that dispatcher / message pumping stuff related to running in a windows / forms application? if i am running a console application should i be fine? – CoderBrien Mar 04 '17 at 07:05
  • There are some nuances in different environments (WinForms, Console App, IIS), but for your case it's not so important. – mukh1n Mar 04 '17 at 07:34
  • By the way, I strongly recommend to read articles by Stephen Cleary about asyncs (http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html). There is all you need to know about async keyword :) – mukh1n Mar 04 '17 at 07:37
1

In order to unwrap the AggregateException, do this:

RunAsync().GetAwaiter().GetResult();
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59