7

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;
Alexandru
  • 12,264
  • 17
  • 113
  • 208

2 Answers2

11

Yes you can do it using the Result property directly after the calling of method:

var result = someClass.myAsyncMethod(someParameter).Result;

and a more better way is to wrap it in Task.Run() to avoid deadlocks like:

var result = Task.Run(() => {

   return someClass.myAsyncMethod(someParameter);

}).Result;

I also found this RunSynchronously() method on MSDN, but that won't server your question as you want a on liner simple code.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • That will await the task to run to completion? – Alexandru Mar 18 '16 at 18:05
  • it will block the caller thread until the task completes returning result – Ehsan Sajjad Mar 18 '16 at 18:06
  • 1
    @EʜsᴀɴSᴀᴊᴊᴀᴅ: can you please show what the syntax is for `Task.Run()`? – Jacob Krall Mar 18 '16 at 18:07
  • 1
    Even using `Task.Run()` can cause deadlocks in some situations that I don't have exact examples for right now. You can see http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously/5097066#5097066 for a more in-depth workaround – willaien Mar 18 '16 at 18:12
  • @EʜsᴀɴSᴀᴊᴊᴀᴅ Thank you for the solution, I did not know `Result` would block. – Alexandru Mar 18 '16 at 18:14
  • @Alexandru but ideally you should be calling async method asyncronously – Ehsan Sajjad Mar 18 '16 at 18:14
  • @EʜsᴀɴSᴀᴊᴊᴀᴅ It depends on the situation ;) – Alexandru Mar 18 '16 at 18:16
  • 2
    @Alexandru It's virtually always wrong. The exceptions would be quite rare. – Servy Mar 18 '16 at 18:20
  • I am not sure about "Result" will be return if Task is non generic. public class Task : Task which have Result property. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TResult Result { get { return IsWaitNotificationEnabledOrNotRanToCompletion ? GetResultCore(waitCompletionNotification: true) : m_result; } } – Mohsin khan Feb 08 '18 at 08:32
4

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();
Jarlotee
  • 51
  • 1