Results 1 to 16 of 16

Thread: [RESOLVED] Can someone explain Asynchronous HttpWebRequests

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Resolved [RESOLVED] Can someone explain Asynchronous HttpWebRequests

    Hi all,

    I need to convert this:

    Code:
    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
    from a synchronous to an asynchronous call. I've read a few examples but I cannot get my head around it at all.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Can someone explain Asynchronous HttpWebRequests

    The asynchronous pattern is basically the same regardless of the object you're using. Instead of calling SomeMethod and waiting until it returns you the data, you call BeginSomeMethod and it returns immediately. You pass a callback as an argument, which is a delegate that refers to a method that you want to be invoked when the asynchronous operation completes. Think of a callback as being much like an event handler. In the callback, you call EndSomeMethod and then get the data.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    So my assignment would happen in the delegate method instead?

    Man I really need to get my head around this stuff.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Can someone explain Asynchronous HttpWebRequests

    That's right. As the name suggests, BeginGetResponse simply begins the process of getting the response. That process occurs in the background while your app carries on with whatever. Once the response has been gotten, your callback method is invoked, you call EndGetResponse and it returns the same data that GetResponse would have.

    Just note that the callback method is executed on a background thread. That means that you will have to marshal a method call to the UI thread if you want to update the UI.

    You might like to follow the VB CodeBank link in my signature and check out my Asynchronous TCP submission. It's not using WebRequests but it does use the same asynchronous pattern.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Can someone explain Asynchronous HttpWebRequests

    Hey Dean,

    You can also see the pattern that John is describing in action here:

    http://msdn.microsoft.com/en-us/libr...se(VS.95).aspx

    Gary

  6. #6

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    Cheers guys I will read the links over the weekend and get my head around it. Thanks!

  7. #7

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    Ok I think I have broken it down some and have the hang of the call. I'm pretty sure ye guys can spot the error, which is of course the fact that the method will terminate before the async code has finished. Putting aside the messy code (I'm learning from it not utilising it) What would be the best way to return the value only when the method is done.

    Anything I have thought off pretty much defeats the purpose of not causing the program to hang in one thread which is what I thought the async stuff was all about.

    Code:
        public class Program
        {
            static HttpWebRequest httpRequest;
            static HttpWebResponse httpResponse;
    
            //Create a string to hold the response from the HTTP Call.
            static string responseAsString = string.Empty;
    
            public static string HttpReader(string url)
            {
                // Create The HTTP Request
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
    
                //// Proxy Stuff here
    
                httpRequest.CookieContainer = new CookieContainer();
                httpRequest.AllowAutoRedirect = true;
                httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
    
                //// Add Cookies Stuff here
    
    
    
                // Get Response Asynchronosly
                HttpAsyncRequest();
    
                // Return String To Caller. This of course fires regardless of the async call.
                return responseAsString;
            }
    
            static void HttpAsyncRequest()
            {
                //This method will only finish when ready
                httpRequest.BeginGetResponse(new AsyncCallback(FinaliseHttpAsyncRequest), null);
            }
    
            static void FinaliseHttpAsyncRequest(IAsyncResult result)
            {
                httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(result);
    
    
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    // Create the stream, encoder and reader.
                    Stream responseStream = httpResponse.GetResponseStream();
                    Encoding streamEncoder = Encoding.UTF8;
                    StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
                    responseAsString = responseReader.ReadToEnd();
                }
                else
                {
                    throw new Exception(String.Format("Response Not Valid {0}", httpResponse.StatusCode));
                }
            }

  8. #8

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    I was thinking of just having a while loop. My thinking is that why its great to do this stuff multithreaded it is stuff I need so the only thing I can do for the user is display a please wait graphic and handle a time out. The while would allow me to run an animation too. Thoughts.

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Can someone explain Asynchronous HttpWebRequests

    What you're now asking for defeats the whole purpose of using an asynchronous method. If you don;t actually want the user to be able to get on with other things in the mean time, don't use an asynchronous method at all.

    In your case, display a modal dialogue with a Marquee ProgressBar or whatever and then start a BackgroundWorker. In the DoWork event handler, call the appropriate synchronous method, then close the dialogue from the RunWorkerCompleted event handler.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  10. #10

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    My mistake, I should have explained,

    This code is a test bed for a windows phone 7 application which doesn't allow the synchronous methods to be called. The fact that my app depends on the connnection though means I cant really go off and do other stuff other than display a marquee of some sort.
    Last edited by DeanMc; Nov 6th, 2010 at 07:59 PM.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Can someone explain Asynchronous HttpWebRequests

    Yeah, you should have explained. That's interesting that you can't call a synchronous method, but that's fine. I'm not sure of the exact limitations of WinPhone but, in general terms, display a dialogue that the user can't close and have it call the asynchronous method. In the callback, once the data has been retrieved, delegate to the UI thread and close the dialogue. That's basically what the BackgroundWorker does anyway: the DoWork event is raised on a ThreadPool thread and, when it completes, a method is called on the UI thread and the RunWorkerCompleted event is raised.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Can someone explain Asynchronous HttpWebRequests

    Hey,

    John, the "limitation" of Windows Phone 7, is also one of it's advantages. The development platform is Silverlight, as a result, you are kind of steered towards doing things in an asynchronous manner.

    Gary

  13. #13

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    Obviously this is not the best example of using async methods. What I wonder is, should I design the app so it never needs to wait for the data? Or is this inevitable ? Technically I could do the requests when the application is first opened, that way the user can do what they need before the app needs it.

  14. #14
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Can someone explain Asynchronous HttpWebRequests

    It really depends.

    If there is nothing for you, or the user to do, while the request is being made, then you could just pop up a spinning gif, to indicate that work is being executed. However, if you can make the request, and allow the user to continue to interact with the UI, then handle the response gracefully, and inform the user when it completes.

    Gary

  15. #15

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2008
    Location
    Rep of Ireland
    Posts
    1,380

    Re: Can someone explain Asynchronous HttpWebRequests

    Food for thought, I will do up a UX story board and see what I can do while the requests are firing. Cheers!

  16. #16
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [RESOLVED] Can someone explain Asynchronous HttpWebRequests

    Sounds like a plan. Let me know how you get on.

    Gary

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width