我想封裝WebClient異步下載方法,以便我可以在等待冗長的文件下載時獲得進度欄更新。 MSDN文檔指出FTPDownloadCompleted和FTPDownloadProgressChanged在不同的線程上,但它們從不觸發。也許我會以錯誤的方式去解決這個問題,但我需要避免同步事件,回調等。所以我想我會嘗試這種方法。 我特別好奇,爲什麼這些事件如果他們是不同線程上的代表,就不會觸發。WebClient.DownloadDataAsync可以封裝在一個類中嗎?
class downloadFTP
{
public delegate void ProgressBarUpdate(Int32 val);
ProgressBarUpdate progressBarUpdate;
WebClient webClient;
Int32 waitTime = 60;
Double percentComplete = 0;
Boolean transferComplete = false;
public Boolean TransferComplete { get { return transferComplete; } }
Byte[] downloadData = null;
public Boolean DownLoadFTPFile(String filename, ProgressBarUpdate pbUpdate)
{
Boolean result = false;
progressBarUpdate = pbUpdate;
AutoResetEvent waiter = new System.Threading.AutoResetEvent (false);
webClient = new WebClient();
webClient.Credentials = new NetworkCredential(user.userId, user.passWd);
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(FTPDownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FTPDownloadProgressChanged);
webClient.DownloadDataAsync(new Uri(ftpURL + "//" + filename),waiter);
waiter.WaitOne(waitTime*1000);
return TransferComplete;
}
private void FTPDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
percentComplete = e.ProgressPercentage;
}
private void FTPDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
downloadData = e.Result;
transferComplete = true;
}
不要忘記在完成時處理WebClient實例(Silverlight中除外)。 – dtb 2010-11-16 21:14:00
謝謝。錯過了。 – Gio 2010-11-16 21:19:47