Posting Concurrent HTTP requests Using Threading

2017-10-18

Using Threads namespace in .net framework we can trigger the concurrent HTTP requests to server. True concurrency can be achieved only when there is more than 1 CPU otherwise it's only a virtual thing that is achieved using swtiching b/w each threads by a single CPU.

A different note about Threading: Threading is useful only when the operation task involved in the threading method is I/O bound or wait for other resources involved. If it's only computational then Threading leverage no advantage & can backfire since there is cost for context switching b/w each threads.


static void Main(string[] args)
        {
while (true)
            {
                List<Thread> lstThreads = new List<Thread>();

                /*
                Thread objThread1 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread1);

                Thread objThread2 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread2);

                Thread objThread3 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread3);

                Thread objThread4 = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                lstThreads.Add(objThread4);


                string fileLocation = @"D:\Asif\JIRA\NEO\Interface Migration\Sprint14\NEORND-3630\Meera\DAO Error\xml4DCRQ.xml";


                objThread1.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series1.xml")));
                objThread2.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series2.xml")));
                objThread3.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series3.xml")));
                objThread4.Start(File.ReadAllText(string.Format("{0}\\{1}", fileLocation, "RTAV_Local_Series4.xml")));
                */

                string fileLocation = @"D:\JIRA\NEO\Sundarbans\Sprint20\NEORND-7568 [Search Connector] Load test optimized codebase\AvailRQMultiPropertySearchRQ.xml";
                for (int i = 1; i <= 30; i++)
                {
                    Thread objThread = new Thread(new ParameterizedThreadStart(DeadLockWithHotelDescriptiveContentNotifRQUpdate));
                    lstThreads.Add(objThread);
                    objThread.Start(File.ReadAllText(fileLocation));
                }


                int ctr = 1;
                foreach (var thread in lstThreads)
                {
                    thread.Join();

                    if (ctr == lstThreads.Count)
                    {
                        Console.WriteLine("All HDC threads finished executing");
                        goto EndWhile;
                    }
                    ctr++;
                }
            }
        EndWhile:
            Console.WriteLine("Press Any key to exit");
            Console.ReadLine();
}
static void DeadLockWithHotelDescriptiveContentNotifRQUpdate(object payload)
        {
            string xmlPayload = (string)payload;
            string response_text = string.Empty;
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;

                //string url = "https://hotfix.hbsconnect.com/app/dm/xml/xml4test";
                string url = "http://127.0.0.1:5000/Search";
                //string url = "http://localhost/app/dm/xml/xml4test";

                HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);
                //-------GETTING WEBPROXY OF LOCAL MACHINE==========//
                WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();

                if (proxy.Address != null)
                {
                    proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                    WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
                }
                //request.Proxy = proxy;
                //----PROXY SET UP===========//


                byte[] bytes = Encoding.UTF8.GetBytes(xmlPayload);
                request.Method = "POST";
                request.Accept = "*/*";
                request.Timeout = 360000; //=6mnts

                request.ContentType = "text/xml"; // text/plain
                request.KeepAlive = false;
                request.ContentLength = bytes.Length;
                request.ProtocolVersion = HttpVersion.Version10;
                //request.ServicePoint.Expect100Continue = true;

                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Flush();


                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    /* 
                    Stream responseStream = response.GetResponseStream();
                    StreamReader Reader = new StreamReader(responseStream, Encoding.Default);
                    response_text = Reader.ReadToEnd();
                    */

                    Stream response_stream = response.GetResponseStream();
                    byte[] byteStream = new byte[512];
                    StringBuilder sbResponse = new StringBuilder();
                    System.Text.Encoding utfEncode = System.Text.Encoding.GetEncoding("utf-8");
                    int byteCount = response_stream.Read(byteStream, 0, 512);
                    while (byteCount > 0)
                    {
                        sbResponse.Append(utfEncode.GetString(byteStream, 0, byteCount));
                        try
                        {
                            byteCount = response_stream.Read(byteStream, 0, 512);
                        }
                        catch
                        {
                            //Micros don't terminate their output stream correctly and just close the connection resulting in an exception at our end
                            byteCount = 0;
                        }
                    }
                    response_text = sbResponse.ToString();
                    if (response_text == string.Empty) response_text = response.StatusCode.ToString();
                }
                stream.Close();
            }
            catch (WebException webEx)
            {
                //throw webEx;
            }
            catch (Exception ex)
            {
                //throw ex;
            }
        }

0 comments: