Can constructors be async?

后端 未结 12 1337
迷失自我
迷失自我 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, 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.

提交回复
热议问题