2 回答

TA贡献1860条经验 获得超9个赞
考虑使用异步事件处理程序和静态HttpClient
static HttpClient client = new HttpClient();
public MainPage() {
InitializeComponent();
loadingData += onLoadingData;
}
protected override void OnAppearing() {
//loadingData -= onLoadingData; //(optional)
loadingData(this, EventArgs.Empty);
base.OnAppearing();
}
private event EventHandler loadingData = delegate { };
private async void onLoadingData(object sender, EventArgs args) {
var model = await GetPatientData();
this.BindingContext = new PatientViewModel(model);
}
public async Task<PatientModel> GetPatientData() {
PatientModel patient = null;
try {
Uri weburl = new Uri("myuri");
Console.WriteLine("a");
var response = await client.GetAsync(weburl);
Console.WriteLine("b");
if (response.IsSuccessStatusCode) {
Console.WriteLine("in");
patient = await response.Content.ReadAsAsync<PatientModel>();
Console.WriteLine("in funciton");
}
}catch(Exception ex) {
Console.WriteLine(ex);
}
return patient;
}
使用这种模式可以帮助避免阻塞调用和套接字耗尽,这有时会导致死锁,从而导致超时。

TA贡献1765条经验 获得超5个赞
尝试这个。
public PatientModel abc { get; set; }
public MainPage()
{
InitializeComponent();
Bridge();
// Using abc
}
public async void Bridge()
{
abc = new PatientModel();
abc = await GetPatientData();
}
public async Task<PatientModel> GetPatientData()
{
PatientModel patient = null;
try
{
Uri weburl = new Uri("myuri");
HttpClient client = new HttpClient();
Console.WriteLine("a");
HttpResponseMessage response = await client.GetAsync(weburl);
Console.WriteLine("b");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("in");
patient = await response.Content.ReadAsAsync<PatientModel>();
Console.WriteLine("in funciton");
return patient;
}
return patient;
}catch(Exception ex)
{
Console.WriteLine(ex);
return patient;
}
- 2 回答
- 0 关注
- 259 浏览
添加回答
举报