Umobuga
Umobuga

Reputation: 33

Is it possible to make object construction asynchronous?

I have an async function that retrieve information from my webservice

private static async Task<DataClass> retrievData(){
...
}

And i need this information on my constructor, but i can't block the rest of my app

so i want to make something like

public class MyClass {
     private DataClass theData;
     public async Myclass(){
          var dataTemp = await Server.retrievData();
          if(dataTemp.ValidatorNumber == Server.Validator.FULL)
              theData = dataTemp
          ...
     }

but this is not allowed. Is there a work-around for this?

Upvotes: 2

Views: 215

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You cannot make a constructor async. However, you can make an async factory method:

public class MyClass {
    private DataClass theData;
    private Myclass(DataClass theData) {
        this.theData = theData;
    }
    public static async MyClass Create() {
        var dataTemp = await Server.retrievData();
        if(dataTemp.ValidatorNumber == Server.Validator.FULL)
              return new DataClass(dataTemp);
        ... // Deal with the error here
    }
}

Now the callers will have a way to make instances of MyClass asynchronously, like this:

var c = await MyClass.Create().ConfigureAwait(false);

Upvotes: 7

Related Questions