Typically async method returns Task class. If you use Wait()
method or Result
property and code throws exception - exception type gets wrapped up into AggregateException
- then you need to query Exception.InnerException
to locate correct exception.
But it's also possible to use .GetAwaiter().GetResult()
instead -
it will also wait async task, but will not wrap exception.
So here is short example:
public async Task MyMethodAsync()
{
}
public string GetStringData()
{
MyMethodAsync().GetAwaiter().GetResult();
return "test";
}
You might want also to be able to return some parameter from async function - that can be achieved by providing extra Action<return type>
into async function, for example like this:
public string GetStringData()
{
return MyMethodWithReturnParameterAsync().GetAwaiter().GetResult();
}
public async Task<String> MyMethodWithReturnParameterAsync()
{
return "test";
}
Please note that async methods typically have ASync
suffix naming, just to be able to avoid collision between sync functions with same name. (E.g. FileStream.ReadAsync
) - I have updated function names to follow this recommendation.