是否可以“加入”? DownloadStringAsync 操作?
我有这样的代码:
public static String Download(string address) {
WebClient client = new WebClient();
Uri uri = new Uri(address);
// Specify a progress notification handler.
client.DownloadProgressChanged += (_sender, _e) => {
//
};
// ToDo: DownloadStringCompleted event
client.DownloadStringAsync(uri);
}
我可以以某种方式加入
此异步请求,而不是在下载完成时在 DownloadStringCompleted
事件处理程序中执行其余代码吗?它将被放置在另一个线程中(这样做是为了让我可以访问下载进度)。我知道 DownloadStringAsync
可以采用第二个参数;手册中名为 userToken
的对象。这能有用吗?谢谢你,
I have this code:
public static String Download(string address) {
WebClient client = new WebClient();
Uri uri = new Uri(address);
// Specify a progress notification handler.
client.DownloadProgressChanged += (_sender, _e) => {
//
};
// ToDo: DownloadStringCompleted event
client.DownloadStringAsync(uri);
}
Instead of having the rest of my code execute in the DownloadStringCompleted
event handler when the download is complete, can I somehow Join
this Async request? It will be housed in another thread (doing it this way so I have access to the download progress). I know that DownloadStringAsync
can take a second parameter; an object called userToken
in the manual. Could this be of use? Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用手动重置事件:
You could use a manual reset event:
我的第一个想法是使用 DownloadString,
DownloadStringAsync
。但是,似乎您必须使用异步方法来获取进度通知。好吧,这没什么大不了的。只需订阅 DownloadStringCompleted 并使用简单的等待像 ManualResetEventSlim 一样处理以阻止直到完成。需要注意的是,我不确定
DownloadStringAsync
是否会发出进度通知。根据 MSDN,DownloadProgressChanged 与某些相关异步方法,但不是DownloadStringAsync
。My first thought would be to use DownloadString, the synchronous version of
DownloadStringAsync
. However, it seems that you must use an async method to get the progress notification. Okay, that's no big deal. Just subscribe to DownloadStringCompleted and use a simple wait handle like ManualResetEventSlim to block until it completes.One note, I am not sure if the progress notification is even raised for
DownloadStringAsync
. According to MSDN, DownloadProgressChanged is associated with some of the async methods, but notDownloadStringAsync
.