C# 如何“检查”、“取消”和等待异步 WebRequest?
假设我开始使用 BeginGetResponse
有 50 个请求。
如何检查每个请求的状态?
以及如何取消它(有时它们会挂起)?
当所有请求都完成或取消时,我该如何执行操作?
Let's say I have 50 requests that I started using BeginGetResponse
.
How do I check the status of each request?
and how do I cancel it (sometimes they hang)?
and how can I perform an action when ALL requests are either completed or canceled?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
BeginGetResponse
的调用返回一个IAsyncResult
。保留对它的引用。您可以使用IAsyncResult.AsyncState
检查请求的状态。要取消请求,请调用原始 WebRequest 实例的
WebRequest.Abort
。要在所有请求完成或取消时执行某些操作,请从每个请求的
IAsyncResult.AsyncWaitHandle
获取 WaitHandle,然后等待所有请求。示例代码此处。The call to
BeginGetResponse
returns anIAsyncResult
. Keep a reference to it. You can use theIAsyncResult.AsyncState
to check the status of the request.To cancel the request, call
WebRequest.Abort
of the original WebRequest instance.To perform something when all requests are completed or cancelled, get a WaitHandle from
IAsyncResult.AsyncWaitHandle
for each of your requests, then wait on them all. Sample code here.您最好实施基于事件的异步模式,以便您的开发能够捕获各个不同阶段的事件。
基本上,我将如何首先创建 IAsyncCommand 接口,如下所示。
根据您的场景实现这两个 CommandProgressChangedEventHander 和 CommandCompletedEventHandler 并相应地填充 Argument。
如果我们假设我们的线程应该检查所讨论的特定 URL 是否是有效的 URL,则代码如下......
AsyncCommandBase 类是一个实现 IAsyncCommand 接口的抽象类。
该类的框架定义如下。
您可以填充进度和已完成事件处理程序,它们的关键是参数填充。你甚至可以用它来填充进度百分比、用户状态等......
You will be better off implementing Event Based Asynchronous Pattern for your development to catch events at all different stages.
Basically, how I would go by first creating an IAsyncCommand interface as follows.
implement those two CommandProgressChangedEventHander and the CommandCompletedEventHandler based on your scenario and populate the Argument accordingly.
If we are assuming that our thread should check whether particular URL in question is an valid URL, the code goes as follows....
The AsyncCommandBase class is an abstract class which implements IAsyncCommand interface.
The skeleton for this class is defined below.
You can populate the Progress and Completed Event handler and they key to is the Argument population. You can even use it for filling the progresspercentage, userstate etc...