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;
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();
Use the Result property on the asynchronous Task, like so: // Synchronous method. void Method()
async/await do not make synchronous code asynchronous. Instead, these keywords make it much easier to code continuations, eliminating ugly boilerplate code.
C# supports both synchronous and asynchronous methods.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With