async
async

Reputation: 45

Asynchronous call C#.Net beginners question

So here I am,got some help from some web tutorials and performing following Asynchronous call. I want to return an object of type UserInfo from following async call. But I'm not sure how the program flows after request.BeginResponse(). Is it something like an additional ref parameter of type UserInfo can be passed to callback method?

        UserInfo GetUserInfoAsync()
        {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Credentials = new NetworkCredential("myID", "myPWD");
        request.Method = "GET";
        request.Accept = "application/json";

        object data = new object();
        RequestState state = new RequestState(request, data, url);
        IAsyncResult asr = request.BeginGetResponse(new AsyncCallback(myCallback), state);
        return null; //Need guidence here;
        }

        private static void myCallback(IAsyncResult result)
        {

        RequestState state = (RequestState)result.AsyncState;
        WebRequest request = (WebRequest)state.Request;
        HttpWebResponse response =(HttpWebResponse)request.EndGetResponse(result);

        Stream s = response.GetResponseStream();
        StreamReader readStream = new StreamReader(s);
        string dataString = readStream.ReadToEnd();

        response.Close();
        s.Close();
        readStream.Close();
        UserInfo ui = ParseJSON(dataString );
        }

Upvotes: 0

Views: 1023

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499800

Your GetUserInfoAsync method will return before the request has completed. That's the meaning of it being asynchronous. You need to make your callback take appropriate action with the UserInfo it's just received - e.g. calling back into the UI thread (using Dispatcher) to update the UI.

You could make your GetUserInfo call wait until it's got a result - but you basically shouldn't. The whole point of asynchronous calls is to avoid blocking.

Upvotes: 1

alxx
alxx

Reputation: 9897

return null; //Need guidence here;

You cannot return anything meaningful at that point. Use event from callback to notify that result is ready.

Upvotes: 0

Jason Goemaat
Jason Goemaat

Reputation: 29194

You need to handle the data in your callback. If you need to return the user info from your initial method call, you need a synchronous operation. There's no way to have that information available until the operation completes.

Upvotes: 0

Related Questions