Extension method 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)
{
    var task = MyAsyncMethod(throwException);
    return task.WaitResultUnwrapException&lt;bool&gt;();
    //or even
    //return MyAsyncMethod(throwException).WaitResultUnwrapException&lt;bool&gt;();
}
async Task&lt;bool&gt; MyAsyncMethod (bool throwException)
{
    if (throwException)
        throw new ArgumentException(nameof(throwException));
    return await Task.Run(() =&gt; true);
}


Example extension method:

using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;

namespace MyCompany.Threading.Tasks
{
    public static class TaskExtensions
    {
        public static T WaitResultUnwrapException&lt;T&gt;(this Task&lt;T&gt; task)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));
            try
            {
                task.Wait();
                return task.Result;
            }
            catch (AggregateException es)
            {
                if (es.InnerExceptions.Count == 1) {
                    var e = es.InnerExceptions[0];
                    ExceptionDispatchInfo.Capture(e).Throw();
                }
                throw;  
            }
        }
        public static void WaitResultUnwrapException(this Task task)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));
            try
            {
                task.Wait();
            }
            catch (AggregateException es)
            {
                if (es.InnerExceptions.Count == 1) {
                    var e = es.InnerExceptions[0];
                    ExceptionDispatchInfo.Capture(e).Throw();
                }
                throw;  
            }
        }
    }
Per the comment by @t3chb0t, all I needed was this:

task.GetAwaiter().GetResult()


In context:

bool MySyncMethod (bool throwException)
{
    return MyAsyncMethod(throwException).GetAwaiter().GetResult(); //this is the only line that's changed
}
async Task&lt;bool&gt; MyAsyncMethod (bool throwException)
{
    if (throwException)
        throw new ArgumentException(nameof(throwException));
    return await Task.Run(() =&gt; true);
}