【发布时间】:2017-01-27 02:57:56
【问题描述】:
我正在尝试使用 Xamarin 快速破解一个基本的移动应用程序以访问本地 API。我在 VS2015 中创建了一个默认的 Xamarin.Forms PCL 项目,并尝试添加代码以访问我在本地运行的 API。但是,当我到达 var response = await client.GetAsync(uri) 行时,代码执行并立即跳回到 RefreshDataAsync() 之后的行,从而绕过了半个函数,包括 try/ 的 catch 和 finally 块捕获声明。我已经在应用程序的每一行添加断点,并且它 100% 不会调用超出 await GetAsync 调用的任何代码。
几个小时后,我不得不承认我对这个应用程序中到底发生了什么感到茫然,因为我以前从未遇到过等待/异步的问题。
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using Xamarin.Forms;
namespace consumerestful
{
public class App : Application
{
private List<Person> people;
public App()
{
// The root page of your application
RefreshDataAsync();
var test = people;
var content = new ContentPage
{
Title = "consumerestful",
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!",
}
}
}
};
MainPage = new NavigationPage(content);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
public async void RefreshDataAsync()
{
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
//RestUrl = http://127.0.0.1:5000/api/
var uri = new Uri(Constants.RestUrl);
try
{
var response = await client.GetAsync(uri);//problem line
//nothing after the above line runs. It jumps back to Line 19(var test = people)
var test = response;
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
people = JsonConvert.DeserializeObject<List<Person>>(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(@" ERROR {0}", ex.Message);
}
finally
{
Debug.WriteLine(@" Finally Block Ran!");
}
}
}
}
【问题讨论】:
标签: c# asynchronous xamarin async-await xamarin.forms