在 Silverlight 中串行处理多个异步 HTTP 请求
由于 Silverlight 4 中通过 WebClient 或 HttpWebRequest 进行 http 访问的异步性质,当我想连续执行多个 http get/posts 时,我发现自己编写的代码如下所示:
doFirstGet(someParams, () =>
{
doSecondGet(someParams, () =>
{
doThirdGet(...
}
});
或类似的代码。我最终会将后续调用嵌套在通常使用某种 lambda 实现的回调中。即使我将内容分解为操作或单独的方法,它仍然难以阅读。
有没有人有一个干净的解决方案来连续执行 SL 4 中的多个 http 请求?
我不需要实际启动所有这些的代码是同步的,但我需要请求串行发生,因此每个请求都需要有效同步。
Due to the async nature of http access via WebClient or HttpWebRequest in Silverlight 4, when I want to do multiple http get/posts serially, I find myself writing code that looks like this:
doFirstGet(someParams, () =>
{
doSecondGet(someParams, () =>
{
doThirdGet(...
}
});
Or something similar. I'll end up nesting subsequent calls within callbacks usually implemented using lambdas of some sort. Even if I break things out into Actions or separate methods, it still ends up being hard to read.
Does anyone have a clean solution to executing multiple http requests in SL 4 serially?
I don't need the code that actually kicks all of this off to be synchronous, but I need the requests to happen serially, so each request needs to be effectively synchronous.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下我关于此的几篇博客文章:-
简单的异步操作运行器 – 第 1 部分
简单异步操作运行器 –第 2 部分
这些文章有点深入,因为它们专注于实际实现,其想法是不必包含花哨的框架来完成此任务。您需要的唯一代码实际上就在文章中,无需下载其他 dll 或 zip 文件。
但请注意,在第 2 部分中,想象如果可以进行同步编码,您的代码会是什么样子。在您的情况下,您的代码将如下所示: -
下一步是修改“do”方法的内容以返回
AsyncOperation
。目前它们可能看起来像这样:-您可以将其转换为:-
第三步是修改您想象的同步代码,如下所示:-
最后对
StuffToDo
的调用更改为:-Take look at a couple of my blog posts on this:-
Simple Asynchronous Operation Runner – Part 1
Simple Asynchronous Operation Runner – Part 2
The articles are a little in depth because they focus on the actual implementation, the idea is not have to include fancy frameworks just to get this done. The only code you need is actually there in the articles, no additional dlls or zip files to download.
However note in part 2 the approach of imagining what your code would look like if synchronous coding were possible. In your case your code would look like this:-
The next step is modify the content of the "do" methods to return an
AsyncOperation
instead. Currently they probably look something like this:-You would convert it to:-
The third step is modify your imaginary synchronous code like this:-
Finally the call to
StuffToDo
changes to:-我遇到过这个问题。我发现协程非常有帮助,我的想法基于 Jeremy Likness 和 Rob Eisenberg 的工作。
此链接将提供更多详细信息。
I have encountered this problem. I found coroutines to be very helpful, I based my ideas on work by Jeremy Likness and Rob Eisenberg.
This link will give more details.