阻止Windows phone中的异步操作

本文关键字:异步操作 phone Windows 阻止 | 更新日期: 2023-09-27 18:05:56

我正在尝试从windows phone发送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();
        }
<<p> Asynronous操作/strong>:
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();
        }

阻止Windows phone中的异步操作

您不是第一个碰到这个问题的人(请参阅是否有可能在wpf (windows phone)中对ui线程进行同步网络调用)。如果你这样做,那么你就会在Windows Phone上死锁UI线程。

最接近的方法是在网络调用中使用async/await。你可以使用一些扩展方法作为NuGet上Microsoft.Bcl.Async包的一部分来完成此操作。