Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# calling async function from constructor gives green underline in VS

say I am doing something async and calling this function from the class constructor:

 public partial class Page_MainMenuDetail : TabbedPage
    {
        ObservableCollection<AdsType> mainList = new ObservableCollection<AdsType>();
        public Page_MainMenuDetail()
        {
            InitializeComponent();
            LoadMainContent(false);
        }

        private async Task LoadMainContent(bool loadMore)
        {
            if (!loadMore)
            {
                mainList = await ReloadAdapter.LoadAllAds(0, 4);
                listview_mainView.ItemsSource = mainList;
            }
            else
            {

            }

        }

My reloadAdapter is just a class that makes an API call and returns an observable collection. But since I await for the reload adapter result, the LoadMainFunction() function has to be async. But that means, that when I call it from inside the constructor it looks like this in the framework (VS):

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The green line indicates that the function is not beeing awaited. Which is true, but I cannot await inside a constructor (as you cannot make a constructor async).

Is this my wrongdoing or is this a common thing?
Ofc I can put the LoadMainContent() into another function that itself is async nbut not a task, and then call that from the constructor, but that is just a workaround to get rid of the green underline.

Or maybe I am doing this concept wrong?

Any ideas?

Best

>Solution :

Indeed, C# / .NET does not currently support async constructors, so you’d have to use either an async static factory method, or an async initialize method after the constructor has finished; however – this line is not true:

that is just a workaround to get rid of the green underline.

This is not just a workaround; if you haven’t awaited an async method, then you don’t know when it has finished, so you can’t rely on the state that it is meant to initialize – and you have have inadvertent thread-safety issues (as you now effectively have two active executions, which is comparable to two active threads). As such, refactoring (in one of the ways cited above) is necessary for correctness.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading