maz*_*ztt 1 c# async-await c#-5.0 dotnet-httpclient windows-phone-8
我是异步的新手,等待编程风格.如何解决以下问题:
我先调用下面的代码.这里的问题是第一行正在等待填充它的需要categoriesvm.Categorieslist,但它没有,但第二行被调用.(我认为这是await的默认行为)
如何确保仅categoriesvm.Categorieslist在第一行中填充第二行时才调用第二行?
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
categoriesvm.GetCategories();
BookCategories.DataContext = from vm in categoriesvm.Categorieslist select vm;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,当我执行第一行时,它会在Categorieslist我上面访问的列表的下方.
public async void GetCategories()
{
Categorieslist = new ObservableCollection<Categories>(await PhoneClient.GetDefaultCategories());
}
Run Code Online (Sandbox Code Playgroud)
在phoneclient下面
public class PhoneClient
{
private static readonly HttpClient client;
public static Uri ServerBaseUri
{
get { return new Uri("http://169.254.80.80:30134/api/"); }
}
static PhoneClient()
{
client =new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
}
public async static Task<List<Categories>> GetDefaultCategories()
{
HttpResponseMessage getresponse = await client.GetAsync(ServerBaseUri + "Categoryss");
string json = await getresponse.Content.ReadAsStringAsync();
json = json.Replace("<br>", Environment.NewLine);
var categories = JsonConvert.DeserializeObject<List<Categories>>(json);
return categories.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
你应该避免async void.我在MSDN文章中解释了这个指南.
将async void方法更改为async Task:
public async Task GetCategoriesAsync()
{
Categorieslist = new ObservableCollection<Categories>(await PhoneClient.GetDefaultCategories());
}
Run Code Online (Sandbox Code Playgroud)
然后就可以await这样:
protected override async void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
await categoriesvm.GetCategoriesAsync();
BookCategories.DataContext = from vm in categoriesvm.Categorieslist select vm;
}
Run Code Online (Sandbox Code Playgroud)
但是,我建议在UI事件之外进行所有VM初始化 - 这将使您的代码更容易测试.看看我的async构造函数博客文章的想法.