HttpWebRequest.BeginGetResponse

20,327

Solution 1

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;
}

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
        }
    } 

Solution 2

The response occurs on a separate thread. Winforms are not multi-thread safe, so you're going to have to dispatch the call on the same thread as the form.

You can do this using the internal message loop of the window. Fortunately, .NET provides a way to do this. You can use the control's Invoke or BeginInvoke methods to do this. The former blocks the current thread until the UI thread completes the invoked method. The later does so asynchronously. Unless there is cleanup to do, you can use the latter in order to "fire and forget"

For this to work either way, you'll need to create a method that gets invoked by BeginInvoke, and you'll need a delegate to point to that method.

See Control.Invoke and Control.BeginInvoke in the MSDN for more details.

There's a sample at this link: https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx

Update: As I'm browsing my profile because I forgot i had an account here - i noticed this and I should add: Anything past 3.5 or when they significantly changed the asynchronous threading model here is out of my wheelhouse. I'm out professionally, and while I still love the craft, I don't follow every advancement. What I can tell you is this should work in all versions of .NET but it may not be the absolute pinnacle of performance 4.0 and beyond or on Mono/Winforms-emulation if that's still around. On the bright side, any hit usually won't be bad outside server apps, and even inside if the threadpool is doing its job. So don't focus optimization efforts here in most cases, and it's more likely to work on "stripped down" platforms you see running things like C# mobile packages although I'd have to look to be sure and most don't run winforms but some spin message loops and this works there too. Basically to bottom line, it's not the "best answer" for the newest platforms in every last case. But it might be more portable in the right case. If that helps one person avoid making a design error, then it was worth the time I took to write this. =)

Solution 3

It's the standard behaviour.

From the documentation on HttpWebRequest.BeginGetResponse Method:

The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. [...] it might take considerable time (up to several minutes depending on network settings) to complete the initial synchronous setup tasks before an exception for an error is thrown or the method succeeds.

To avoid waiting for the setup, you can use HttpWebRequest.BeginGetRequestStream Method but be aware that:

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.

Solution 4

You can use BackgroundWorker add do the whole thing in DoWork

Share:
20,327
ceth
Author by

ceth

I'm a programmer, occasional SRE, Unix automator. I'm currently working primarily in Go, and prior to that my weapon of choice was Python, but I'm also familiar with Java, C#, JavaScript, and bash. I dabble in Clojure and F# but I've never thrown a big problem at it. I run Linux at home and at work but that doesn't mean I'm ignorant of other systems :)

Updated on July 09, 2022

Comments

  • ceth
    ceth almost 2 years

    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);
    

    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?

  • ceth
    ceth about 12 years
    What is IAsyncResult parameter in the second method ? Result of calling request.BeginGetResponse() ?
  • ceth
    ceth about 12 years
    As I see it doesn't change anything. Here is full code pastebin.com/trvq1qza. GUI windows freeze on line 18.
  • ceth
    ceth about 12 years
    In my windows the main window is freezing, i can not move window and don't see mouse cursor over window :(
  • Mustafa Ekici
    Mustafa Ekici about 12 years
    @demas is that wpf application right? if not look for chross threading on internet
  • Corey
    Corey over 3 years
    How to get HttpWebResponse from FinishWebRequest?