我仍在努力学习 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;
}
知道发生了什么吗?
谢谢。