使用Monotouch中的HttpWebRequest.GetRequestStream()进行WebException超时

时间:2013-10-01 20:18:45

标签: c# ios .net xamarin.ios xamarin

我仍在努力学习Xamarin.iOs并随机(有时在模拟器上,但更多时候在设备上),我在异步方法中调用HttpWebRequest.GetRequestStream()的超时异常。但是,每次调用方法时我都会创建一个新的HttpWebRequest,我认为我正确地关闭并处理了所有内容。以下是代码片段:

private async static Task<T> internalCallService<T>(ILogger logger,string url, string body, string httpVerb, string contentType)
{
    T result = default(T);
    WebRequest wr=null;
    try
    {
        logger.Log("Calling {0} started", url);
        wr = HttpWebRequest.Create(url);
        wr.ContentType = contentType;
        wr.Method = httpVerb;
        wr.Timeout = DEFAULT_TIMEOUT;
        byte[] streamContent = System.Text.Encoding.UTF8.GetBytes(body);
        using (Stream dataStream = wr.GetRequestStream())
        {
            dataStream.Write(streamContent, 0, streamContent.Length);
            dataStream.Flush();
            dataStream.Close();
            var sw = new Stopwatch();
            sw.Start();
            using (var response = (await wr.GetResponseAsync().ConfigureAwait(false)))
            {
                if (response != null)
                {
                    sw.Stop();
                    logger.Log("Time to call {0} : {1} ms", url, sw.ElapsedMilliseconds);
                    try
                    {
                        var webResponse = response as HttpWebResponse;
                        if (webResponse != null && webResponse.StatusCode == HttpStatusCode.OK)
                        {
                            using (Stream responseStream = webResponse.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(responseStream))
                                {
                                    var responseText = reader.ReadToEnd();
                                    result = JsonConvert.DeserializeObject<T>(responseText);
                                    reader.Close();
                                }
                                responseStream.Close();
                            }
                        }
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        logger.Log(e.GetBaseException().Message);
        throw;
    }
    finally
    {
        if (wr != null)
        {
            wr.Abort();
            wr = null;
        }
    }

    return result;
}

知道发生了什么事吗?

感谢。

0 个答案:

没有答案