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

Time:03-07

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

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

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related