这是我的方法:
private static void UpdatePref(List<EmailPrefer> prefList)
{
if(prefList.Count > 0)
{
foreach (EmailPref pref in prefList)
{
UpdateEmailRequest updateRequest = new UpdateEmailRequest(pref.ID.ToString(), pref.Email, pref.ListID.ToString());
UpdateEmailResponse updateResponse =(UpdateEmailResponse) updateRequest.SendRequest();
if (updateResponse.Success)
{
Console.WriteLine(String.Format("Update Succsesful. ListID:{0} Email:{2} ID:{1}", pref.ListID, pref.Email, pref.ID));
continue;
}
Console.WriteLine( String.Format("Update Unsuccessful. ListID:{0} Email:{2} ID:{1}\n", pref.ListID, pref.Email, pref.ID));
Console.WriteLine(String.Format("Error:{0}", updateResponse.ErrorMessage));
}
Console.WriteLine("Updates Complete.");
}
Console.WriteLine("Procses ended. No records found to update");
}
该列表有大约84个有效记录,它正在循环并发送API请求。但它在第3次API调用时停止,只处理84条记录中的2条。当我调试以查看发生了什么时,我只看到它在我的SendRequest方法中停止,而没有吐出任何错误。它停在GetRequestStream上,当我走到那里并尝试继续踩踏时,它就停止了,我的应用程序停止运行而没有任何错误!
HttpWebRequest request = CreateWebRequest(requestURI, data.Length);
request.ContentLength = data.Length;
request.KeepAlive = false;
request.Timeout = 30000;
// Send the Request
requestStream = request.GetRequestStream();
跆拳道?最终,如果我让它继续运行,我会收到错误“操作已超时”。但那么为什么前2个电话会通过,而这个电话会超时?我不明白。
另外,第二个问题。让它在我的foreach中创建一个用于发送和接收的新对象是否效率低下?但这就是我如何删除这些类并要求发送电子邮件,ListID等是发送该类API调用的要求。我只是不知道在foreach中通过每次迭代创建一个新实例是否正常。可能很常见,但对我来说只是感到奇怪和低效。
答案 0 :(得分:1)
编辑:您似乎已经在评论中回答了您自己的问题。
我没有这方面的个人经验,但似乎您需要在获取响应后在HTTP Web请求上调用close。打开连接的数量限制为2,并且在关闭()之前不会释放连接。请参阅http://blogs.msdn.com/feroze_daud/archive/2004/01/21/61400.aspx,其中提供了以下代码来演示您所看到的症状。
for(int i=0; i < 3; i++) {
HttpWebRequest r = WebRequest.Create(“http://www.microsoft.com“) as HttpWebRequest;
HttpWebResponse w = r.GetResponse() as HttpWebResponse;
}
答案 1 :(得分:0)
超时的一种可能性是你正在与之交谈的服务器会限制你。您可能会尝试在每次更新后插入一个延迟(一秒钟,可能是?)。
假设UpdateEmailRequest
和UpdateEmailResponse
分别来自WebRequest
和WebResponse
,那么按照您的方式创建请求并不是特别低效。这是非常标准的。但是,请注意WebResponse
是IDisposable
,这意味着它可能会分配非托管资源,您应该通过调用Dispose
方法来处置它。像这样:
UpdateEmailResponse updateResponse =(UpdateEmailResponse) updateRequest.SendRequest();
try
{
if (updateResponse.Success)
{
Console.WriteLine(String.Format("Update Succsesful. ListID:{0} Email:{2} ID:{1}", pref.ListID, pref.Email, pref.ID));
continue;
}
Console.WriteLine( String.Format("Update Unsuccessful. ListID:{0} Email:{2} ID:{1}\n", pref.ListID, pref.Email, pref.ID));
Console.WriteLine(String.Format("Error:{0}", updateResponse.ErrorMessage));
}
finally
{
updateResponse.Dispose();
}
我想有可能不处理响应对象会保持与服务器的开放连接,并且服务器因超出开放连接而超时。