Aditya patil
Aditya patil

Reputation: 115

How to get return value from Task wait()

I have one async method which returns value and I want to wait for the completion of this task.

var return = Task.Run(() => SomeMethod(param1)).Wait();

How can I get return value from above this line.

Upvotes: 7

Views: 19047

Answers (2)

anwar alomari
anwar alomari

Reputation: 1

var result = await Task.Run(() => SomeMethod(param1));

Upvotes: 0

JonasH
JonasH

Reputation: 36371

The typical method would be to just write

 var result = Task.Run(() => SomeMethod(param1)).Result;

This will block until the result becomes available. So it is equivalent to

var task = Task.Run(() => SomeMethod(param1));
task.Wait();
return task.Result;

Note that using .Result is generally not recommended. It will block the calling thread, so there is little point not just using var result = SomeMethod(param1). There is also the risk of deadlocks. If this is run on the UI thread, and SomeMethod uses .Invoke or something else that waits for the UI thread, then your program will deadlock.

The generally recommended method is to use async/await: var result = await Task.Run(...)

Upvotes: 17

Related Questions