Can asynchronous methods be called in the constructor?
This problem often arises when trying to integrate asynchronous code into class constructors. Specifically, the goal of this example is to call the getWritings()
method (which parses JSON data) during object instantiation.
The problem
Initially, calling getWritings()
directly in the constructor and making it an async method resulted in a null return value and an empty LongListView
. Trying to get the result via getWritings().Result
to resolve this issue causes the UI thread to block.
Solution
The recommended approach is to design your application to handle the asynchronous nature of data retrieval. The constructor should set up a view to indicate that the data is being downloaded, and the actual data update should occur after the download is complete.
Additional resources on this topic include a blog post on async constructors, an MSDN article on asynchronous data binding in MVVM scenarios, and an MSDN article on async best practices, which emphasizes avoiding async void
The importance of method.
The above is the detailed content of Can Async Methods Be Called Within Constructors?. For more information, please follow other related articles on the PHP Chinese website!