【发布时间】:2018-04-24 18:28:17
【问题描述】:
所以我正在尝试使用 FTP 下载文件并希望在进度条组件上显示当前进度。我使用自定义 FtpClient 类运行这样的任务:
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
pBar.Visibility = Visibility.Visible;
string status = "";
string filename = entry.FileName.Text;
await Task.Run(() =>
{
status = client.DownloadFile(filename, sfd.FileName, pBar);
});
statusBox.Text = status.Substring(4);
}
public string DownloadFile(string source, string dest, ProgressBar pBar)
{
FtpWebRequest sizeRequest = CreateRequest(CombinePaths(url, source), WebRequestMethods.Ftp.GetFileSize); // creates FtpWebRequest and assigns method
FtpWebResponse sizeResponse = (FtpWebResponse)sizeRequest.GetResponse();
if (sizeResponse.ContentLength <= 0) // if server does not support SIZE
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false; // fails here since progress bar is in the another thread
pBar.Maximum = sizeResponse.ContentLength;
pBar.Value = 0;
}
byte[] buffer = new byte[buffSize];
using (FtpWebResponse dlResponse = (FtpWebResponse)dlRequest.GetResponse())
{
using (Stream stream = dlResponse.GetResponseStream())
{
using (FileStream fs = new FileStream(dest, FileMode.OpenOrCreate))
{
int readCount = stream.Read(buffer, 0, buffSize);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
pBar.Value = pBar.Value + readCount;
readCount = stream.Read(buffer, 0, buffSize);
}
}
}
return dlResponse.StatusDescription;
}
有没有办法让它工作?由于我正在下载并尝试更新 UI,我不知道是否有办法做我想做的事
【问题讨论】:
-
您应该将 UI 控件更新包装在
Application.Current.Dispatcher.BeginInvoke函数中,例如Application.Current.Dispatcher.BeginInvoke(new Action(() => { pBar.IsIndeterminate = false; pBar.Maximum = sizeResponse.ContentLength; pBar.Value = 0; }));
标签: c# wpf asynchronous progress-bar