我可以';当我使用HttpWebRequest和HttpWebResponse时,它不会停止UI线程,当它调用Wa

本文关键字:UI Wa 调用 线程 HttpWebResponse 我可以 HttpWebRequest | 更新日期: 2023-09-27 18:00:30

    void method1() 
    {
        url = "http://192.168.5.22/mobile/testpost.php" ;     
        request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = true;
        //// request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
        RequestState myRequestState = new RequestState();
        myRequestState.Request = request;
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), myRequestState);
        event_2.WaitOne();
        String s = myRequestState.responseAsString;
        String g = s;
    }
    private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
    { 
        RequestState myrequestobj = (RequestState)AsyncResult.AsyncState;
        HttpWebRequest myrequest = myrequestobj.Request;
        response = (HttpWebResponse)myrequest.EndGetResponse(AsyncResult);
        string test1;
        test1 = ((HttpWebResponse)response).StatusDescription;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // Create the stream, encoder and reader.
            Stream responseStream = response.GetResponseStream();
            var x =response.GetResponseStream();
            //Encoding streamEncoder = Encoding.UTF8;
            StreamReader responseReader = new StreamReader(responseStream);
            responseAsString = responseReader.ReadToEnd();
            myrequestobj.responseAsString = responseAsString;
        }
        else
        {
            throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
        }
        event_2.Set();
    }

我可以';当我使用HttpWebRequest和HttpWebResponse时,它不会停止UI线程,当它调用Wa

HttpWebRequest方法似乎将部分工作委派给UI线程。以下是我遇到的死锁情况的堆栈跟踪的一部分:

...
System.Windows.dll!System.Net.Browser.AsyncHelper.BeginOnUI(System.Net.Browser.BeginMethod beginMethod, System.AsyncCallback callback, object state) + 0x9b bytes
System.Windows.dll!System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(System.AsyncCallback callback, object state) + 0x25 bytes
...

请注意BeginGetResponse后面的BeginOnUI。"异步"回调实际上与UI线程同步,因此在UI线程被阻止时挂起。HttpWebResponse方法可能正在执行相同类型的同步。