Can constructors be async?

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

    Constructor acts very similarly to a method returning the constructed type. And async method can't return just any type, it has to be either “fire and forget” void, or Task.

    If the constructor of type T actually returned Task<T>, that would be very confusing, I think.

    If the async constructor behaved the same way as an async void method, that kind of breaks what constructor is meant to be. After constructor returns, you should get a fully initialized object. Not an object that will be actually properly initialized at some undefined point in the future. That is, if you're lucky and the async initialization doesn't fail.

    All this is just a guess. But it seems to me that having the possibility of an async constructor brings more trouble than it's worth.

    If you actually want the “fire and forget” semantics of async void methods (which should be avoided, if possible), you can easily encapsulate all the code in an async void method and call that from your constructor, as you mentioned in the question.

    0 讨论(0)
  • 2020-11-22 09:37

    I would use something like this.

     public class MyViewModel
        {
                public MyDataTable Data { get; set; }
                public MyViewModel()
                   {
                       loadData(() => GetData());
                   }
                   private async void loadData(Func<DataTable> load)
                   {
                      try
                      {
                          MyDataTable = await Task.Run(load);
                      }
                      catch (Exception ex)
                      {
                           //log
                      }
                   }
                   private DataTable GetData()
                   {
                        DataTable data;
                        // get data and return
                        return data;
                   }
        }
    

    This is as close to I can get for constructors.

    0 讨论(0)
  • 2020-11-22 09:40

    if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;

    MyClass instance = new MyClass();
    instance.Foo(); // null exception here
    

    That's why they don't allow this i guess.

    0 讨论(0)
  • 2020-11-22 09:50

    I'm not familiar with the async keyword (is this specific to Silverlight or a new feature in the beta version of Visual Studio?), but I think I can give you an idea of why you can't do this.

    If I do:

    var o = new MyObject();
    MessageBox(o.SomeProperty.ToString());
    

    o may not be done initializing before the next line of code runs. An instantiation of your object cannot be assigned until your constructor is completed, and making the constructor asynchronous wouldn't change that so what would be the point? However, you could call an asynchronous method from your constructor and then your constructor could complete and you would get your instantiation while the async method is still doing whatever it needs to do to setup your object.

    0 讨论(0)
  • 2020-11-22 09:52

    you can use Action inside Constructor

     public class ViewModel
        {
            public ObservableCollection<TData> Data { get; set; }
           public ViewModel()
            {              
                new Action(async () =>
                {
                      Data = await GetDataTask();
                }).Invoke();
            }
    
            public Task<ObservableCollection<TData>> GetDataTask()
            {
                Task<ObservableCollection<TData>> task;
                //Create a task which represents getting the data
                return task;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 09:52

    I use this easy trick.

    public sealed partial class NamePage
    {
      private readonly Task _initializingTask;
    
      public NamePage()
      {
        _initializingTask = Init();
      }
    
      private async Task Init()
      {
        /*
        Initialization that you need with await/async stuff allowed
        */
      }
    }
    
    0 讨论(0)
提交回复
热议问题