从 Silverlight 中的服务调用返回对象

发布于 2024-12-02 12:06:52 字数 957 浏览 0 评论 0原文

我需要在 Silverlight 库中实现一个方法,该方法通过 httpwebrequest 调用(非 wcf-)服务,获取响应,然后填充一个对象并返回它。

因为这是 Silverlight,所以响应会异步返回,因此我无法确定应在何处填充该对象以及应如何返回它。

这是我到目前为止的代码:

    public MyObject GetMyObject 
    {
        HttpWebRequest req = WebRequest.Create(MyUri) as HttpWebRequest;
        req.Method = "GET";
        req.Accept = "application/json";

        req.BeginGetResponse((cb) =>
        {
            HttpWebRequest rq = cb.AsyncState as HttpWebRequest;
            HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; 
            string result;
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                result = reader.ReadToEnd();
                reader.Close();
            }                
        }, req);

    }

我想我可以在执行 reader.ReadToEnd() 之后立即填充该对象,但是我实际上在哪里返回它?我无法在回调函数内返回它,但如果我在 GetMyObject() 末尾返回它,则不能保证自异步回调以来会填充该对象。

提前致谢!

I need to implement a method in a Silverlight library, which calls a (non-wcf-)service via httpwebrequest, gets the response, then populates an object and returns it.

Because this is Silverlight, response comes back asynchronously, so I'm having trouble figuring out where this object should be populated and how it should be returned.

This is the code I have so far:

    public MyObject GetMyObject 
    {
        HttpWebRequest req = WebRequest.Create(MyUri) as HttpWebRequest;
        req.Method = "GET";
        req.Accept = "application/json";

        req.BeginGetResponse((cb) =>
        {
            HttpWebRequest rq = cb.AsyncState as HttpWebRequest;
            HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; 
            string result;
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                result = reader.ReadToEnd();
                reader.Close();
            }                
        }, req);

    }

I think I can populate the object right after I do reader.ReadToEnd(), but where do I actually return it? I can't return it inside the callback function, but if I return it at the end of GetMyObject(), the object is not guaranteed to be populated since of the asynch callback.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反差帅 2024-12-09 12:06:52

首先,您需要认识到,当一系列操作(我们通常称为“代码”)包含异步完成的操作时,整个序列实际上是异步的。

在同步世界中,我们有返回指定类型的函数。在异步世界中,这些函数返回 void,而是将委托传递给它们以进行调用(我们称之为回调),其中委托接受指定类型的参数。

由于您的函数在内部进入异步世界,因此它也必须(因为它已成为现在异步的序列的一部分)。所以它的签名需要改变。现在看起来像这样:-

    public void GetMyObject(Action<MyObject> returnResult)
    {
        HttpWebRequest req = WebRequest.Create(MyUri) as HttpWebRequest;
        req.Method = "GET";
        req.Accept = "application/json";

        req.BeginGetResponse((cb) =>
        {
            WebResponse resp = req.EndGetResponse(cb);
            string json;
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                json = reader.ReadToEnd();
                reader.Close();
            }
            MyObject result = SomethingDoDeserialiseJSONToMyObject(json);
            returnResult(result);
        }, null);

    }

然后您可以使用以下方法调用此方法:-

  GetMyObject(result => 
  {
       Dispatcher.BeginInvoke(() =>
       {
            //  Display result in UI
       });
  });

First of all you need to recognise that when a sequence of operations (which we usually call "code") includes an operation that completes asynchronously then the whole sequence is in fact asynchronous.

In the synchronous world we have functions that return a specified type. In the asynchronous world those functions return void and instead have delegates passed to them to be called (we call them callbacks) where the delegate accepts a parameter of the specified type.

Since your function internally steps into the asynchronous world so it must also (since it has become part of a sequence which is now asynchronous). So its signature needs to change. It would now look like this:-

    public void GetMyObject(Action<MyObject> returnResult)
    {
        HttpWebRequest req = WebRequest.Create(MyUri) as HttpWebRequest;
        req.Method = "GET";
        req.Accept = "application/json";

        req.BeginGetResponse((cb) =>
        {
            WebResponse resp = req.EndGetResponse(cb);
            string json;
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                json = reader.ReadToEnd();
                reader.Close();
            }
            MyObject result = SomethingDoDeserialiseJSONToMyObject(json);
            returnResult(result);
        }, null);

    }

You would then call this method using as follows approach:-

  GetMyObject(result => 
  {
       Dispatcher.BeginInvoke(() =>
       {
            //  Display result in UI
       });
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文