System.Net.Http.HttpClient超时似乎被忽略了

时间:2015-09-15 14:44:04

标签: c# xamarin xamarin.ios xamarin.forms xamarin.mac

我正在使用Xamarin.iOS版本:8.10.5.26(独立版)并面临一个非常奇怪的行为,超时请求与HttpClient()一起发送:

以下代码尝试从url获取结果,并且有60秒超时(1分钟),但是当请求被触发时,超时大约需要90秒。拨打电话时,我手动关闭网络连接以检查超时。据观察,它需要超过60秒。

CODE

public async Task<Dictionary<string,object>> GetPatientDataASync (string lUsername)
    {
        var lDict = new Dictionary<string,object> ();
        try {
            string lQuerystring = "{Email: '" + lUsername + "'}";
            String lUrl = String.Format (Constants.mURLPatient + "?where={0}", JObject.Parse (lQuerystring));
            var lClient = new HttpClient ();
            lClient.BaseAddress = new Uri (lUrl);
            lClient.DefaultRequestHeaders
                .Accept
                .Add (new MediaTypeWithQualityHeaderValue ("application/json"));
            lClient.DefaultRequestHeaders.Add ("X-Parse-Application-Id", Constants.mKeyParseAppId);
            lClient.DefaultRequestHeaders.Add ("X-Parse-REST-API-Key", Constants.mKeyRestAPIKey);
            lClient.Timeout = new TimeSpan (0, 1, 0);
            var request = new HttpRequestMessage ();
            request.Method = HttpMethod.Get;
            if (Utility.isNetworkConnected ()) {
                bool responseStatus = false;
                await lClient.SendAsync (request)
                    .ContinueWith (responseTask => {
                    if (responseTask != null) {
                        var response = responseTask.Result;
                        if (response != null) {
                        if (response.IsSuccessStatusCode) {
                                var responseContent = response.Content;
                                if (responseContent != null) {
                                    string responseString = responseContent.ReadAsStringAsync ().Result;
                                    if (!string.IsNullOrWhiteSpace (responseString)) {
                                        JObject json = JObject.Parse (responseString);
                                        if (json != null) {
                                            if (json ["results"].Any ()) {
                                                Patient user = Patient.Instance;
                                                user.objectId = json.SelectToken (@"results[0].objectId").Value<string> ();
                                                user.Email = json.SelectToken (@"results[0].Email").Value<string> ();
                                                user.Name = json.SelectToken (@"results[0].Name").Value<string> ();
                                                user.IsNotificationsEnabled = json.SelectToken (@"results[0].IsNotificationsEnabled").Value<string> ();

                                                Application.Current.Properties ["IsNotificationsEnabled"] = json.SelectToken (@"results[0].IsNotificationsEnabled").Value<string> ();

                                                if (json.SelectToken (@"results[0].DeviceToken") != null) {
                                                    var deviceToken = json.SelectToken (@"results[0].DeviceToken").Value<JArray> ();
                                                    if (deviceToken != null)
                                                        user.DeviceToken = deviceToken.ToObject < List<string>> ();
                                                } else {
                                                    user.DeviceToken = new List<string> ();
                                                }

                                                var doctors = json.SelectToken (@"results[0].MyDoctors").Value<JArray> ();
                                                user.AllergicTo = json.SelectToken (@"results[0].AllergicTo").Value<string> ();
                                                user.ContactNo = json.SelectToken (@"results[0].ContactNo").Value<string> ();
                                                user.BloodGroup = json.SelectToken (@"results[0].BloodGroup").Value<string> ();
                                                user.MyDoctors = doctors != null ? doctors.ToObject<List<string>> () : new List<string> ();
                                                responseStatus = true;
                                            } else
                                                responseStatus = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
              lDict.Add (SUCCESS_CODE, responseStatus);
                return lDict;
            } else {
                lDict.Add (NO_INTERNET, Constants.mStringNoInternetMessage);
                return lDict;
            }
        } catch (Exception e) {
            Debug.WriteLine (e.Message + "\n " + e.StackTrace);
            lDict.Add (EXCEPTION_OCCURED, e);
            return lDict;
        }
    }

如果我的代码中有错误,请告诉我。 此处也报告了相同的问题: -

  1. First link

  2. Second Link

2 个答案:

答案 0 :(得分:0)

这是一个多年来已经多次打开,关闭和重新打开的知识错误。已经报告了herehere

答案 1 :(得分:0)

有解决方法:

  1. 定义CancellationTokenSource并将Token设置为http请求;
  2. CancellationTokenSource cts.CancelAfter(timeout);上的超时取消取消try { } catch(TaskCanceledException) { if(!cts.Token.IsCancellationRequested) {// timeout } else {//other reason } }
  3. 不要忘记捕捉异常,就像这样。
  4. {{1}}