Reputation: 97
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
Reputation: 61
You have few options like
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
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