这个异步下载可以吗? WebClient.DownloadDataAsyn() 问题
我有一个名为 SiteAsyncDownload.cs 的类,
代码如下:
public class SiteAsyncDownloader
{
WebClient Client = new WebClient();
string SiteSource = null;
/// <summary>
/// Download asynchronously the source code of any site in string format.
/// </summary>
/// <param name="URL">Site URL to download.</param>
/// <returns>Website source code - string.</returns>
public string GetSite(string URL)
{
Uri Site = new Uri(URL);
Client.DownloadDataAsync(Site);
Client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(FinishedDownloading);
//Don't know if this would work. Consult with StackOverflow.
while (true)
{
if (SiteSource != null)
{
return SiteSource;
}
}
}
void FinishedDownloading(object sender, DownloadDataCompletedEventArgs e)
{
SiteSource = Encoding.ASCII.GetString(e.Result);
throw new NotImplementedException();
}
}
我不是 100% 确信它能按我希望的方式工作。我希望该类异步下载所需的任何内容,并在下载完成后返回字符串。这是正确的方法吗?
例如,下面是我打算如何使用它的示例:
SiteAsyncDownloader Downloader = new SiteAsyncDownloader();
/// <summary>
/// Search for a movie using only a name.
/// </summary>
/// <param name="MovieName">Movie name.</param>
public void SearchMovie(string MovieName)
{
string SearchURL = FormatSearch(MovieName);
string SearchSource = Downloader.GetSite(SearchURL);
string MovieURL = FindMovieURL(SearchSource);
string MovieSource = Downloader.GetSite(MovieURL);
FindInformation(MovieSource);
}
在 SearchMovie() 方法的第二行代码中,我的程序会因为异步下载而崩溃吗?我怎样才能考虑到这一点并使其正常工作?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在这里尝试执行的操作:
只会启动 CPU 直至操作完成,从而打破了异步操作的初衷。您需要使用事件模式或回调模式。
What you're trying to do here:
Will just spin up the CPU until the operation is done, defeating the point of it being asynchronous in the first place. You would need to use the event pattern or the callback pattern.
虽然它可能会起作用,但这是一个坏主意。如果您要立即阻塞直到结果出来,那么使用异步 API 就没有意义。如果在获得数据之前您确实无法在该线程中执行任何其他工作,并且您只有一个请求,则只需使用同步 API。此外,您阻止的方式只是紧密循环,这将导致您的处理器无缘无故地旋转。
在稍微不同的问题上,如果我是你,我不会使用
Encoding.ASCII
- 你应该尊重服务器发送的任何编码。使用DownloadStringAsync
是最简单的方法。While it will probably work, it's a bad idea. There's no point in using asynchronous APIs if you're immediately going to block until the results have come through. If you really can't do any more work in that thread until you've got the data, and you've only got one request, just use a synchronous API. Further, the way you're blocking is to just tight loop, which will cause your processor to spin for no reason.
On a slightly different matter, I wouldn't use
Encoding.ASCII
if I were you - you should honour whatever encoding the server sends. UsingDownloadStringAsync
is the easiest way of doing that.