dkilov fuss
dkilov fuss

Reputation: 97

Async methods return type

In the code I have await in WallModel method but I can't use async. How can I use async and await in this code?

class WallModel
{
    public WallModel()
    {
        WallItems = new ObservableCollection<Wall>();
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("XXXXX");
        string Parse_Text = await response.Content.ReadAsStringAsync();


    }
    public ObservableCollection<Wall> WallItems { get; set; }
}

Upvotes: 1

Views: 99

Answers (2)

Star Wolf
Star Wolf

Reputation: 61

  1. In order to use await, method needs to have "async Task" in declaration
  2. async constructors are not allowed.

You have few options like

  1. Use asynchronous factory pattern and don't do initialization in constructor
  2. Use asynchronous initialization pattern

If you have to go with the first option, your code may look like something like this

class WallModel
{
    public WallModel()
    {
        WallItems = new ObservableCollection<Wall>();            

        Initialization = InitializeAsyn();
    }

    public Task Initialization { get; private set; }

    private async Taks InitializeAsyn()
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("XXXXX");
        string Parse_Text = await response.Content.ReadAsStringAsync();
    }

    public ObservableCollection<Wall> WallItems { get; set; }
    }
}

and then somewhere outside of the class

var instance = new WallModel();
await instance.Initialization;

Good article on the subject and how you can do it (as author mentioned in other answer) http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Your WallModel method is actually a constructor and it can't be marked async, so you can't use await within it's body either.

Upvotes: 2

Related Questions