2010-11-16 73 views
0

我想封裝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; 
    } 
+0

不要忘記在完成時處理WebClient實例(Silverlight中除外)。 – dtb 2010-11-16 21:14:00

+0

謝謝。錯過了。 – Gio 2010-11-16 21:19:47

回答

0

Web客戶端上運行當前SynchronizationContext回調(見AsyncOperationManager.CreateOperation)。

如果當前SynchronizationContext是一個WinForms或WPF事件循環,那麼您的DownLoadFTPFile方法將阻止線程和事件不會顯示出來。解決方案:刪除AutoResetEvent。

+0

刪除AutoResetEvent會破壞目的。我希望在下載文件或超時時返回,同時更新進度欄。我有一個循環,其中有一個thread.sleep調用,但認爲這會更容易。 – Gio 2010-11-16 21:19:12

相關問題