0

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?

rb_
  • 11
  • 2
  • 2
    Yes, the `await` operator: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/await – Gabriel Luci Jan 19 '23 at 02:34
  • The Microsoft docs have a well-written series of articles on [Asynchronous programming with async and await](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) that are worth the read. – Gabriel Luci Jan 19 '23 at 02:35
  • BTW, using `await` like that (which is the correct way) doesn't do what you probably think it does. However it does act (or appear to act) as if it does – Flydog57 Jan 19 '23 at 03:07
  • Related: [How to call asynchronous method from synchronous method in C#?](https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) and also [Calling async method synchronously](https://stackoverflow.com/questions/22628087/calling-async-method-synchronously). – Theodor Zoulias Jan 19 '23 at 04:43

1 Answers1

1
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.

KnuturO
  • 1,565
  • 15
  • 19
  • But then the method where we use await operator must be marked as async. How to avoid this? – rb_ Jan 19 '23 at 12:44