我有這個類叫做SiteAsyncDownload.cs這是異步下載工作嗎? WebClient.DownloadDataAsyn()的問題
下面的代碼:
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()方法,將我的程序崩潰,因爲它是異步下載?我如何考慮這一點並使其正常工作?
喬恩,我只使用異步方法,所以我的GUI不凍結,而我的程序下載網站的源代碼。我的代碼是否會凍結源代碼? 另一個說明,我有點新的網絡抓取。而不是使用encoding.ASCII,我可以使用什麼來下載我的網站源代碼以用於我的抓取目的? – 2009-10-20 21:17:23
Argh ...錯字。 *我的代碼是否會凍結我的GUI? – 2009-10-20 21:17:59
它會鎖定GUI,因爲你的'while(true)'只是在一個_very_緊密循環中進行,直到檢索到該值爲止,這會使得所有的CPU時間離開GUI。 – mgbowen 2009-10-20 21:21:04