c# - Xamarin HttpClient 方法 GetAsync 超时错误
问题描述
我创建了一个 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;
}
使用这种模式可以帮助避免阻塞调用和套接字耗尽,这有时会导致死锁,从而导致超时。
推荐阅读
- c# - 使用多个文本框搜索数据库 Asp.net
- ruamel.yaml - 如何安装没有原生扩展的 ruamel.yaml
- java - 来自前端的信息永远不会到达后端(jsp)
- scala - 将 org.apache.spark.mllib.linalg.Matrix 转换为 Scala 中的 spark 数据帧
- android - AsyncTask 下载网页内容失败
- r - R:使用seat from、seat to、n.tickets创建座位号
- angular - ERROR 错误:找不到带有路径的控件
- java - 如果我在子类中有一个方法请求超类的对象,我如何区分两者?
- python - Jupyter notebook (Python 3.6): ImportError: cannot import name 'prange'
- scala - Scala:捕获交互式外部进程的标准输出/标准错误