我需要向Web资源发出异步请求并使用此页面中的示例(
link to full example):
HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com"); RequestState myRequestState = new RequestState(); myRequestState.request = myHttpWebRequest; // Start the asynchronous request. IAsyncResult result= (IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);
但是当我测试应用程序时,执行冻结(在2-3秒内)在此代码的最后一行(我可以使用调试器观察它).
解决方法
你可以试试,我相信那更好
private void StartWebRequest(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.BeginGetResponse(new AsyncCallback(FinishWebRequest),request); } private void FinishWebRequest(IAsyncResult result) { HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse; }
因为textBox’值的chross线程,但是这是wpf应用程序我会重拍这个,顺便说一下你可以使用webclient之类的
private void tbWord_TextChanged(object sender,TextChangedEventArgs e) { WebClient wc = new WebClient(); wc.DownloadStringCompleted += HttpsCompleted; wc.DownloadStringAsync(new Uri("http://en.wikipedia.org/w/api.PHP?action=opensearch&search=" + tbWord.Text)); } private void HttpsCompleted(object sender,DownloadStringCompletedEventArgs e) { if (e.Error == null) { //do what ever //with using e.Result } }