Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 595
Alexandru Avatar asked Mar 18 '16 18:03

Alexandru


People also ask

Can we call asynchronous method from another synchronous method?

Solution A If you have a simple asynchronous method that doesn't need to synchronize back to its context, then you can use Task. WaitAndUnwrapException : var task = MyAsyncMethod(); var result = task. WaitAndUnwrapException();

Can we call async method from Sync C#?

Use the Result property on the asynchronous Task, like so: // Synchronous method. void Method()

Does async await run synchronously?

async/await do not make synchronous code asynchronous. Instead, these keywords make it much easier to code continuations, eliminating ugly boilerplate code.

Is C sharp synchronous?

C# supports both synchronous and asynchronous methods.


2 Answers

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.

like image 110
Ehsan Sajjad Avatar answered Nov 14 '22 22:11

Ehsan Sajjad


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();
like image 32
Jarlotee Avatar answered Nov 14 '22 22:11

Jarlotee