线程化HttpWebResponse并不总是会触发

时间:2018-08-24 02:00:25

标签: c# multithreading web-services

此代码正在Web服务中运行。有时它执行得很好,有时似乎线程没有发出对URL的调用。我也从未见过在HttpWebResponse using语句中编写的日志事件。我不确定发生了什么,请帮忙吗?

HttpWebRequest urlRequest = (HttpWebRequest)WebRequest.Create(url);
urlRequest.Method = "POST";
byte[] data = Encoding.ASCII.GetBytes(JSON);
urlRequest.ContentLength = data.Length;
urlRequest.ContentType = "application/json";

ThreadPool.QueueUserWorkItem(o =>
                    {
                        try
                        {
                            new Logger().Info("data length = " + data.Length.ToString());
                            new Logger().Info(JSON);
                            new Logger().Info("Before posting to ERPFullAppointmentCheckout controller");
                            using (Stream stream = urlRequest.GetRequestStream())
                            {
                                stream.Write(data, 0, data.Length);

                                new Logger().Info("Before using HttpWebResponse");
                                using (HttpWebResponse response = (HttpWebResponse)urlRequest.GetResponse())
                                {
                                    new Logger().Info("Inside using HttpWebResponse");
                                    string receivedresponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
                                    string statuscode = response.StatusCode.ToString();
                                    new Logger().Info("Response from POST: " + (String.IsNullOrEmpty(receivedresponse) ? "" : receivedresponse));
                                    new Logger().Info("Status Code: " + statuscode);
                                }
                            }


                            new Logger().Info("After posting to ERPFullAppointmentCheckout controller");
                        }
                        catch (Exception ex)
                        {
                            new Logger().Error("Error posting to ERPFullAppointmentCheckout controller", ex);
                        }
                    });

1 个答案:

答案 0 :(得分:0)