Suppose I have this (heavily redacted) function written in C# to run on .NET 6.
string DoThing(string myParam)
{
/* Pre-processing redacted. */
var resultOfGet = await xyz.GetAsync(thingToGet);
/* Post-processing redacted. */
return processedThing;
}
This fails with an error
The await operator can only be used within an async method
I've found similar questions on this site with this exact error and and the answer is almost uniformly to change the function signature to async and return a Task
value.
This won't work for me. I don't want to send await calls up the chain, I need my function to take a string parameter and return a string value. Is there a way to call an async function as if it were a regular function?
Answering anticipated questions...
Does the library you're using have a non-async
Get
alongsideGetAsync
?
Alas, no.Why don't you want to your function to be async?
It would break something else.You should fix the "something else" then.
This isn't an "XY" question. I could take you by the hand and show you what I'm doing, but we're only ever going to end up needing to wait for an async function to finish and get the results.This question is a duplicate.
If so, that's great, but please check there's an answer that doesn't approximate addingasync
to the calling function. If it doesn't, I'm asking a very different question.Doesn't the
Task
object returned have a member function to wait for the result and return it?
If it does, I couldn't find it. The name of that function would make a great answer to my question.If the function is written as async it'll block the calling thread if you do wait for the result the way you want to.
I am 100% happy to do that and willing to accept all responsibility for my decision.