# Extension method to to run any async method synchronously

Sometimes I need to call async code from a synchronous method. This leads to repetition in code to wait for the task to complete, then ensure that the expected exception is thrown instead of an aggregate exception (assuming there's only 1 exception returned, as is the case unless we're iterating through a list / something like that; in which case we preserve the AggregateException as that's then expected by the handling code).

To avoid repetition, would a helper function called and defined as below be appropriate? Does something like this already exist in the framework?

Example calling code:

bool MySyncMethod (bool throwException)
{
//or even
//return MyAsyncMethod(throwException).WaitResultUnwrapException<bool>();
}
{
if (throwException)
throw new ArgumentException(nameof(throwException));
}


Example extension method:

using System;
using System.Runtime.ExceptionServices;

{
{
{
try
{
}
catch (AggregateException es)
{
if (es.InnerExceptions.Count == 1) {
var e = es.InnerExceptions[0];
ExceptionDispatchInfo.Capture(e).Throw();
}
throw;
}
}
{
try
{
}
catch (AggregateException es)
{
if (es.InnerExceptions.Count == 1) {
var e = es.InnerExceptions[0];
ExceptionDispatchInfo.Capture(e).Throw();
}
throw;
}
}
}

• ps. After posting I just thought that we may be iterating a list / with catch logic defined to build an aggregate exception, but only have 1 exception returned; in which case the exception type would differ from expected... Therefore I'd likely change the above to add a preserveAggegateException parameter to avoid unwrapping aggregates where they're expected. if (!preserveAggegateException && es.InnerExceptions.Count == 1) – JohnLBevan Nov 26 '18 at 17:20
• mhmm... I think this is not necessary as task.GetAwaiter().GetResult() will also unwrap the exception with much less code, see this on Stack Overflow. – t3chb0t Nov 26 '18 at 17:25
• Thanks; I'd not seen that approach; definitely makes sense / covers pretty much exactly what I've done above with less effort and the same caveat around moving you away from the benefits of being asynchronous. Thanks @t3chb0t. – JohnLBevan Nov 26 '18 at 17:31

task.GetAwaiter().GetResult()


In context:

bool MySyncMethod (bool throwException)
{
return MyAsyncMethod(throwException).GetAwaiter().GetResult(); //this is the only line that's changed
}