我正在尝试封装WebClient异步下载方法,这样我就可以在等待冗长的文件下载时获得进度条更新。 MSDN文档表明FTPDownloadCompleted和FTPDownloadProgressChanged在不同的线程上,但它们永远不会触发。也许我会以错误的方式解决这个问题,但我需要避免同步事件,回调等等......所以我想我会尝试这条路线。 我特别好奇为什么如果他们是不同线程的代表,事件就不会被解雇。
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 :(得分:0)
WebClient在当前SynchronizationContext上运行回调(请参阅AsyncOperationManager.CreateOperation)。
如果当前的SynchronizationContext是WinForms或WPF事件循环,那么您的DownLoadFTPFile
方法会阻止该线程,并且事件不会显示。解决方案:删除AutoResetEvent。