Can constructors be async?

后端 未结 12 1124
迷失自我
迷失自我 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:54

    Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok.

    public class ViewModel       
    {       
        public ObservableCollection Data { get; set; }       
    
        //static async method that behave like a constructor       
        async public static Task BuildViewModelAsync()  
        {       
            ObservableCollection tmpData = await GetDataTask();  
            return new ViewModel(tmpData);
        }       
    
        // private constructor called by the async method
        private ViewModel(ObservableCollection Data)
        {
            this.Data = Data;   
        }
    }  
    

提交回复
热议问题