在代码中,我在WallModel方法中等待,但我不能使用异步。如何在此代码中使用async和await?
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; }
}
答案 0 :(得分:2)
您的WallModel
方法实际上是constructor,并且无法标记为async
,因此您无法在其正文中使用await
。
答案 1 :(得分:0)
你有几个选项,比如
如果你必须使用第一个选项,你的代码可能看起来像这样
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; }
}
}
然后在课堂外的某个地方
var instance = new WallModel();
await instance.Initialization;
关于这个主题的好文章以及你如何做到(正如作者在其他答案中提到的那样)http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html。