Sunday, December 23, 2018

Limit the Number of Concurrent Requests in C#

The following code illustrates how to limit concurrent requests in C#:

            //Create the collection of data to POST to the RESTlet
            List<int> orderIDs = new List<int>();

            //this will create a list of 10 order ids that will be sent to the RESTlet concurrently via POST
            for (var i = 0; i < 900; i++) { int ID = 10000 + i; orderIDs.Add(ID); }

            //Create a parallelOptions object and set the maximum number of concurrent requests
            ParallelOptions options = new ParallelOptions() { MaxDegreeOfParallelism = 10 };

            //Include the options when sending the concurrent/parallel requests
            Parallel.ForEach(orderIDs, options, orderID =>
                    //create instance of the web request
                    WebRequest request = WebRequest.Create("");
                    request.ContentType = "application/json";
                    request.Method = "POST";
                    request.Headers.Add("Authorization:NLAuth nlauth_account=819157,,nlauth_signature=dummypassword,nlauth_role=3");

                    //string jsonString = "{\"orderid\":" + orderID + "}";

                    string jsonString = "{\"tracking\":\"1ZAE80030330574135\",\"status\":\"shipped\",\"shipmethod_orig\":\"U11\",\"shipdate\":20120816,\"orderid\":";
                    jsonString += orderID;
                    jsonString += ",\"trackingurl\":\"\",\"shipmethod\":1496}";

                    //write json string on the request body
                    using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(jsonString); }

                    //send request and get response
                    WebResponse response = request.GetResponse();

The sample code contains dummy credentials.

No comments:

Post a Comment