开发者

Asynchronous call C#.Net beginners question

开发者 https://www.devze.com 2023-01-16 00:30 出处:网络
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

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 = readS开发者_如何学运维tream.ReadToEnd();

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


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.


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.


return null; //Need guidence here;

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

0

精彩评论

暂无评论...
验证码 换一张
取 消