阻止Windows手机中的异步操作

时间:2013-03-26 03:26:10

标签: c# windows-phone-7 asynchronous windows-phone-8

我正在尝试从Windows手机发送http帖子到服务器,我通过发送帖子数据得到一些问题。我把断点放在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();
        }

1 个答案:

答案 0 :(得分: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包的一部分,您可以使用扩展方法来执行此操作。