我需要向 REST 服务发送 40 个请求,并且我想我可能会尝试使其并行以节省一些时间,因为每个 http 请求需要接近一秒钟。
我在下面粘贴了一段我的代码(为了说明而简化)来展示我的方法。当我并行执行它时,大约 40 条消息中有 8 条返回状态代码 500 -“内部服务器错误”。如果我在“正常”foreach 循环中执行它,一切都很好。
我的问题是,我是否以错误的方式并行化/执行此操作,或者它可能是另一端的代码?
Parallel.ForEach(Messages, message=>
try
{
//Create a HttpWebRequest, ie. request.GetRequestStream()
HttpWebRequest httpWebRequest = request.GetWebRequest(uri, RequestType.PUT,message);
using (var webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//You should make sure you read the response stream, even if you don't care about the response.
//This should help not producing too many lingering connections.
new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
lock (lockObject)
{
//Collect errors in a list
responses.Add("Something went wrong" + webResponse.StatusCode);
}
}
}
}
catch (WebException web)
{
var response = (HttpWebResponse)web.Response;
lock (lockObject)
{
//Collect errors in a list
responses.Add("Something went wrong" + webResponse.StatusCode); }
}
catch (Exception e)
{
lock (lockObject)
{
//Collect errors in a list
responses.Addstring.Format("Unspecified Error:{0}", e)}); }
}
});