Robert
Robert

Reputation: 3501

Windows Phone C# Asynchronous get https request

I want to implement asynchronous get-request via https. This is needed to separate UI and request threads. This code works find but I am not sure is it truly asynchronous. Please provide performance critics of this code.

public void authHttp()
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("uri");
        request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
    }

    private void ReadWebRequestCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

        using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
        {
            string results = httpwebStreamReader.ReadToEnd();
            //TextBlockResults.Text = results; //-- on another thread!
            //Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
        }
        myResponse.Close();
    }

Upvotes: 3

Views: 1055

Answers (2)

Shawn Kendrot
Shawn Kendrot

Reputation: 12465

Yes, it is executed Async. You can confirm by debugging, putting a break point in the ReadWebRequestCallback method and stepping over (F10) the BeginGetResponse call in the authHttp method. When you do this, you'll notice that your breakpoint is not hit. It will be hit later.

Upvotes: 2

Peter Ritchie
Peter Ritchie

Reputation: 35881

BeginGetResponse (I'm assuming that's called on a UI thread) is asynchronous. that will call ReadWebRequestCallback on a different thread than the UI thread. BeginGetResponse uses asynchronous UI so, it may not use a "thread" to do the IO work--that might get offloaded to hardware. But, it does use another thread pool thread to invoke your callback.

It's also a good idea to continue doing asynchronous operations in the callback. ReadToEnd is synchronous. As long as you've blocked the thread the asynchronous IO subsystem used for your session, it's likely blocked from doing any other asynchronous IO until you unblock and return from the callback. If you're using .NET 4.5, look at StreamReader.ReadtoEndAsync. If not, you'll have to use drop down to Stream.BeginRead and loop until all data is received.

Upvotes: 2

Related Questions