Can constructors be async?

后端 未结 12 1248
迷失自我
迷失自我 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 09:58

    Some of the answers involve creating a new public method. Without doing this, use the Lazy class:

    public class ViewModel
    {
        private Lazy> Data;
    
        async public ViewModel()
        {
            Data = new Lazy>(GetDataTask);
        }
    
        public ObservableCollection GetDataTask()
        {
            Task> task;
    
            //Create a task which represents getting the data
            return task.GetAwaiter().GetResult();
        }
    }
    

    To use Data, use Data.Value.

提交回复
热议问题