Consider this rather simple method:
private bool ValidateKey(HttpRequestMessage message)
{
}
The above method is called as follows
if (!ValidateKey(request))
{
//do something
}
Now I want to call a method inside ValidateKey which returns Task. Let's assume it is the ReadAsStringAsync method in HttpRequestMessage:
message.Content.ReadAsStringAsync();
Now since this method can run asynchronously I should ideally call it like this:
string output = await message.Content.ReadAsStringAsync();
But this will require me to change my method signature to include async and the return type to Task and then the caller too... ad infinitum.
It is possible to call ReadAsStringAsync synchronously, i.e, I am willing to have ValidateKey wait till ReadAsStringAsync completes. This will save me the trouble of changing the code just to cater to this one method.
No. If the operation is inherently asynchronous you can't run it synchronously. You can however block the thread and wait for it to complete.
I would highly advise against doing that though. You should make your operation async
all the way or don't bother using an async operation at all.
You can also use AsyncContext by Stephen Cleary:
string output = AsyncContext.Run(() => message.Content.ReadAsStringAsync());
If you still plan on blocking then use GetAwaiter().GetResult()
as it's closer in exception handling to what await
would do:
string output = message.Content.ReadAsStringAsync().GetAwaiter().GetResult();
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