views:

134

answers:

3

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 );
        }
+1  A: 

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.

Jon Skeet
This is a part of an API that sits between an Application and Web API.Dispatcher.BeginInvoke() doesn't seem to work in this context.What else would be a possible solution?
async
@async: What do you mean by "doesn't seem to work"? Other solutions would include making the caller pass in a callback to be executed when the UserInfo has been fetched and decoded.
Jon Skeet
A: 

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.

Jason Goemaat
A: 
return null; //Need guidence here;

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

alxx