Reputation: 11
Is there an easy way in .net to wait for an async function to fetch its returned result?
I wrote code like this but maybe there is a standard solution?
T WaitForResult<T>(Func<Task<T>> async)
{
Task<T> task = async.Invoke();
task.Wait();
return task.Result;
}
e.g.
async Task<string> f()
{
...
}
void g()
{
string str = WaitForResult( () => f() );
}
If we use await instead that, the g
function would have to be marked as async. How to avoid this?
Upvotes: 0
Views: 92
Reputation: 1635
async Task<string> f()
{
...
}
Is called by
string s = await f();
If you are calling from a non async function and you cannot change this you can use.
string s = f().GetAwaiter().GetResult();
or
string s = f().Result;
But this is not recommend as it kinda brakes the async pattern.
Upvotes: 1