Octopus系列之UploadValues异步上载

时间:2022-04-22 19:48:14

不多说了直接上代码

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string uriString = "http://127.0.0.1/tools/Handler1.ashx";
            WebClient myWebClient = new WebClient();
            NameValueCollection myNameValueCollection = new NameValueCollection();
            myNameValueCollection.Add("Name", "Tom");
            myNameValueCollection.Add("Address", uriString);
            myNameValueCollection.Add(");

            //虽然是异步调用 但是还会阻止当前的响应,所以从效果上看,还是会阻塞,这不是我想要的方式
            //应该使用后台线程 去做这样的事情
            //这个和控制台展示的效果不一样
            myWebClient.UploadValuesCompleted += myWebClient_UploadValuesCompleted;
            myWebClient.UploadValuesAsync(new Uri(uriString), null, myNameValueCollection, context);

            //同步POST
            //byte[] responseArray = myWebClient.UploadValues(uriString, myNameValueCollection);
            //Decode and display the response.
            //Response.Write(Encoding.ASCII.GetString(responseArray));
            //context.Response.Write("Hello World");
        }

        void myWebClient_UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
        {
            Octopus.Common.CommonHelper.TraceLog(Encoding.ASCII.GetString(e.Result));
        }

        //接收
        context.Response.ContentType = "text/plain";
        System.Threading.Thread.Sleep();
        context.Response.Write("Hello World," + context.Request.Form["Name"] + ","
                + context.Request.Form["Age"] + "," + context.Request.Form["Address"]);