As far as I understand, when you want to wait until async method is completed, you have to use await. Otherwise, it's thread will be detached and you'll never hear back from it again. But when you use await, you then have to make the enclosing method async as well (Why though?). That means, you have to use async-await all the way up the call stack. That also means, you can't await-async in constructors.
async Task<int> Boo()
{
return 1;
}
async Task Far()
{
int res = await Boo();
}
Is there a way to stop this infestation? Meaning, how to execute Boo
synchronously and get the result, without having to make Far
async ?
EDIT:
Does this answer your question? How to cancel a Task in await?
No, I need to get task done, not cancel it.
That also means, you can't await-async in constructors. - why would you want to?
I really don't, but it looks like I have to.
Task.Result is only the answer if you like deadlocks. Why are you trying so hard to avoid async/await?
- the
project is huge
- for some
external methods
there are no reason to run them async, though they declared as such - using results of async operations in
constructors
"you then have to make the enclosing method async as well" - no. you can wait for the result synchronously by accessing Task.Result
Using Task.Result
looks like the answer, but right now I'm unable to compile with it. Supposedly, RunSynchronously()
should also be able to solve problem?
because you don't want half-baked objects if you can help it.
Sure, I don't. Ideally, I want to synchronously get the result of external method, marked async and finish object initialization.
Don't do work in constructors
Good point, but I just can't help myself.
RESOLUTION:
Seems like .GetAwaiter().GetResult();
was just enough to do the trick for me. I would consider this an answer, if the question was not marked duplicate.