[英]Xamarin HttpClient method GetAsync timeout error
我創建了一個API來獲取數據,但它顯示超時錯誤。 我正在Xamarin的主要功能內部調用該功能,該功能在運行應用程序時被調用。
public MainPage()
{
InitializeComponent();
//this.BindingContext = new PatientViewModel();
Task<PatientModel> abc = GetPatientData();
}
我的API GetAsync調用函數:
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;
}
}
}
代碼未顯示任何錯誤。 當執行轉到GetAsync語句時,它會等待一段時間並發生異常。
System.Net.WebException: The request timed out. ---> Foundation.NSErrorException: Exception of type 'Foundation.NSErrorException' was thrown.
考慮將異步事件處理程序與靜態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;
}
使用此模式可以幫助避免阻塞調用和套接字耗盡,這有時會導致死鎖,從而導致超時。
嘗試這個。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.