How can I await an async method without an async modifier in this parent method?
How can I await an async method without an async modifier in this parent method?
That's kind of like asking "how can I write an application using C# but without taking a dependency on any kind of .NET runtime?"
Short answer: don't do that.
Really, what you're doing here is taking a naturally-synchronous method (Update
), making it appear asynchronous by running it on a thread pool thread (UpdateDataAsync
), and then you're wanting to block on it to make the asynchronous method appear synchronous (Save
). Serious red flags.
I recommend you carefully study Stephen Toub's famous pair of blog posts should I expose asynchronous wrappers for my synchronous methods and should I expose synchronous wrappers for my asynchronous methods. The answer to both questions is "no", though Stephen Toub explains several options to do it if you really have to.
That "really have to" should be reserved for the application level. I assume these methods (Update
, UpdateDataAsync
, and Save
) are in different layers of the application (e.g., data / data service / view model). The data / data service layers should not be doing synchronous/asynchronous conversions. The view model (application-specific) level is the only one that has an excuse to do that kind of conversion -- and it should only do so as a last resort.
Edit: this answer was before the Task.Run was added. With that extra context, the scenario is best described as "don't do that".
You can access .Result
or use .Wait()
, but you need to know how the task is implemented first. In particular, you need to know whether it uses sync-context. The reason this is important is that if it does this could deadlock immediately, because some sync-contexts need the calling context to exit completely (for example, MVC's sync-context needs to leave the controller's action method).
To guard against this is hard, but you should probably always explicitly specify a timeout with a call to .Wait()
- just in case.