Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a method that returns Task<T> to run synchronously?

Tags:

c#

async-await

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.

like image 703
bobbyalex Avatar asked Dec 20 '22 05:12

bobbyalex


1 Answers

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();
like image 66
i3arnon Avatar answered Jan 12 '23 00:01

i3arnon