0

REST サービスに 40 のリクエストを送信する必要があります。各 HTTP リクエストには 1 秒近くかかるため、時間を節約するために並列処理を試みることを考えていました。

私のアプローチを示すために、私のコードのセクション (説明のために簡略化されています) を以下に貼り付けました。並行して実行すると、40 個のメッセージのうち約 8 個がステータス コード 500 - 'Internal server Error' を返します。「通常の」 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)}); }
            }
        });
4

0 に答える 0