HttpWebRequest.BeginGetResponse [英] HttpWebRequest.BeginGetResponse
本文介绍了HttpWebRequest.BeginGetResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要向Web资源发出异步请求,并使用此页面中的示例(链接到完整示例):
I need to make async request to web resource and use example from this page (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秒)(我可以使用调试器观看它).
But when I am testing the application the execution freeze(on 2-3 sec) on the last line of this code (i can watch it using debugger).
为什么?是我的错误还是该函数的标准行为?
Why? Is it my mistake or it is a standard behaviour of the function?
推荐答案
您可以尝试一下,我敢肯定那是更好的
You can try, I m sure thats better
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;
}
由于文本框值的交叉线程,但这是wpf应用程序,我会重新标记它,顺便说一句,您可以像这样使用webclient
Because of chross thread of textbox'value,But this is wpf application i will retag this, btw you can use webclient like
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
}
}
这篇关于HttpWebRequest.BeginGetResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文