开发者

How an Asynchronous call communicate to UI

开发者 https://www.devze.com 2023-01-16 11:51 出处:网络
A Windows Phone application referencing a dll(another class library project). There is an asynchronous webrequest in the dll to request a server and parse the response.

A Windows Phone application referencing a dll(another class library project). There is an asynchronous webrequest in the dll to request a server and parse the response.

Click event of a button in the main page of WinPhone application calls the asynchronous method of referenced dll.The callback method raises an event when the response is received and parsed. Now when event raises I have the parsed object till HTTPcommunication layer. Simply how to show a mess开发者_JS百科age box with this result in the UI when HTTPcommunication module is done with its work.

public class HTTPRequester
{
    public delegate void ResponseReceievedAndParsedDelegate(HTTPRequester eventRaiser, object result);
    public event ResponseReceievedAndParsedDelegate ResponseReceivedAndParsed;

    public void GetUserInformation(string userid)
    {

        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Credentials = new NetworkCredential("uid", "pwd");
        request.Method = "GET";
        request.Accept = "application/json";
        object data = new object();
        RequestState state = new RequestState(request, data);
        IAsyncResult asr = request.BeginGetResponse(new AsyncCallback(RequesterCallback), state);


    }

    void RequesterCallback(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();



        HTTPResponseParser grp = new HTTPResponseParser();
        UserInfo ui = grp.ParseUserInformation(dataString );
        state.Response = ui;

        if (ResponseReceivedAndParsed != null)
        {
            ResponseReceivedAndParsed(this, ui);
        }
    }
}



      (asynchronous)

MainUI------>HTTCommunicator--------->Server

MainUI HTTPCommunicator<--------Server

My problem is how to make the missing link to pass the response from HTTPCommunicator back to Main UI.

Hope I didn't confuse you guys. Could anyone point to some code sample,if this can be done with Dispatcher.


In UI cerate method:

private void HandleMessage(HTTPRequester eventRaiser, object result)
{
   UserInfo ui = (UserInfo)result;
   //show message
}

After creating HttpRequester attach to its event:

HttpRequester xxx = new ...
xxx.ResponseReceivedAndParsed += new ResponseReceievedAndParsedDelegate(HandleMessage);
0

精彩评论

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

关注公众号