Sunday, December 23, 2018

Sample C# Code of sending concurrent requests to RESTlets

The following is a sample code on how to send concurrent requests to RESTlets:

            //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 < 10; i++) { int ID = 10000 + i; orderIDs.Add(ID); }
            //Loop through each item in orderIDs and send each concurrently
            Parallel.ForEach(orderIDs, 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=123456,,nlauth_signature=password,nlauth_role=3");

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

                    //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();
            MessageBox.Show("Send Request Completed!");

1. The number of threads(concurrent requests) would automatically be calculated by the system using a formula and the number of cores your system has.

2. The order in which the orderIDs are sent do not necessarily depend on their position on the list of order IDs.

No comments:

Post a Comment