从 Silverlight 中的服务调用返回对象
我需要在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要认识到,当一系列操作(我们通常称为“代码”)包含异步完成的操作时,整个序列实际上是异步的。
在同步世界中,我们有返回指定类型的函数。在异步世界中,这些函数返回 void,而是将委托传递给它们以进行调用(我们称之为回调),其中委托接受指定类型的参数。
由于您的函数在内部进入异步世界,因此它也必须(因为它已成为现在异步的序列的一部分)。所以它的签名需要改变。现在看起来像这样:-
然后您可以使用以下方法调用此方法:-
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:-
You would then call this method using as follows approach:-