1

我正在尝试将 http post 从 windows phone 发送到服务器,我通过发送 post 数据遇到了一些问题。我将断点放在 button_click_1 函数中,我发现它不会启动异步操作。除此之外,它还阻塞了当前线程,我知道这种情况是由allDone.waitOne().

为什么异步操作不起作用以及如何解决?

感谢您的任何帮助。

private void Button_Click_1(object sender, RoutedEventArgs e)
            {
            // Create a new HttpWebRequest object.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "application/x-www-form-urlencoded";

            request.Method = "POST";

            // start the asynchronous operation
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

            allDone.WaitOne();

        }

异步操作

private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;


            // End the operation
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            string postData = "xxxxxxxxxxx";    
            // Convert the string into a byte array. 
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Write to the request stream.
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();

            // Start the asynchronous operation to get the response
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

            // End the operation
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();
            tbtesting.Text = responseString.ToString();

            streamResponse.Close();
            streamRead.Close();

            response.Close();
            allDone.Set();
        }
4

1 回答 1

1

您不是第一个遇到此问题的人(请参阅Is it possible to make synchronous network call on ui thread in wpf (windows phone))。如果您这样做,那么您将死锁 Windows Phone 上的 UI 线程。

您将获得的最接近的方法是在网络调用中使用 async/await。作为 NuGet 上的 Microsoft.Bcl.Async 包的一部分,您可以使用一些扩展方法来执行此操作。

于 2013-03-26T06:48:07.723 回答