首页 > 解决方案 > 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.

标签: c#apixamarin

解决方案


考虑使用异步事件处理程序和静态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;
}

使用这种模式可以帮助避免阻塞调用和套接字耗尽,这有时会导致死锁,从而导致超时。

参考Async/Await - 异步编程的最佳实践

参考您使用 HttpClient 错误


推荐阅读