Is there a way to synchronously run a C# task and get the result in one line of code?

Viewed 11179

I have an async method which works when I call it as follows:

var result = await someClass.myAsyncMethod(someParameter);

Is it possible to do something like this, but in one line of code?

var task = someClass.myAsyncMethod(someParameter);
task.RunSynchronously();
var result = task.Result;
2 Answers

If you find yourself doing this often you can write a small extension

public static class TaskExtensions
{
    public static T SyncResult<T>(this Task<T> task)
    {
        task.RunSynchronously();
        return task.Result;
    }
}

Then you can use:

var result = Task.SyncResult();
Related