c# – HttpWebRequest.BeginGetResponse

前端之家收集整理的这篇文章主要介绍了c# – HttpWebRequest.BeginGetResponse前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要向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
        }
    }
原文链接:https://www.f2er.com/csharp/243139.html

猜你在找的C#相关文章