Can constructors be async?

后端 未结 12 1339
迷失自我
迷失自我 2020-11-22 09:18

I have a project where I\'m trying to populate some data in a constructor:

public class ViewModel
{
    public ObservableCollection Data { get;          


        
12条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 10:02

    In this particular case, a viewModel is required to launch the task and notify the view upon its completion. An "async property", not an "async constructor", is in order.

    I just released AsyncMVVM, which solves exactly this problem (among others). Should you use it, your ViewModel would become:

    public class ViewModel : AsyncBindableBase
    {
        public ObservableCollection Data
        {
            get { return Property.Get(GetDataAsync); }
        }
    
        private Task> GetDataAsync()
        {
            //Get the data asynchronously
        }
    }
    

    Strangely enough, Silverlight is supported. :)

提交回复
热议问题