大佬教程收集整理的这篇文章主要介绍了windows-phone-7 – 如何在主线程中获得异步结果,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我的问题是:
在下面的代码示例中,请告诉我如何在Main方法中获得“responseString(string)”?
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx
using System; using System.Net; using System.IO; using System.Text; using System.Threading; class HttpWebRequestBeginGetRequest { private static ManualResetEvent allDone = new ManualResetEvent(false); public static void Main(string[] args) { // Create a new HttpWebRequest object. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx"); request.ContentType = "application/x-www-form-urlencoded"; // Set the Method property to 'POST' to post data to the URI. request.Method = "POST"; // start the asynchronous operation request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request); // Keep the main thread from continuing while the asynchronous // operation completes. A real world application // Could do something useful such as updating its user interface. allDone.WaitOne(); /* I'd like to get "responseString" here. */ } private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the operation Stream postStream = request.EndGetRequestStream(asynchronousResult); Console.WriteLine("Please enter the input data to be posted:"); string postData = Console.ReadLine(); // Convert the string into a byte array. byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Write to the request stream. postStream.Write(byteArray,postData.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(new AsyncCallback(GetResponseCallback),request); } private static 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(); /* I'd like to get this responseString in Main method. */ Console.WriteLine(responseString); // Close the stream object streamResponse.Close(); streamRead.Close(); // Release the HttpWebResponse response.Close(); allDone.Set(); } }
要从后台线程导航到另一个页面,您可以使用Dispatcher.
//Method to move to next page. Can be called from GetResponseCallBack private void NavigateToNextPage() { Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("Page2.xaml",UriKind.Relative")); }); }
以上是大佬教程为你收集整理的windows-phone-7 – 如何在主线程中获得异步结果全部内容,希望文章能够帮你解决windows-phone-7 – 如何在主线程中获得异步结果所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。