我有一个进度条,显示后台工作人员 do_dowork 事件返回的进度,如下所示。
if (ftpSourceFilePath.Scheme == Uri.UriSchemeFtp)
{
FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(ftpSourceFilePath);
NetworkCredential objCredential = new NetworkCredential(userName, password);
objRequest.Credentials = objCredential;
objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
int len = 0;
int iProgressPercentage = 0;
FileStream objFS = new FileStream((cd+"\\VolareUpdate.rar"), FileMode.Create, FileAccess.Write, FileShare.Read);
while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
{
objFS.Write(buffer, 0, len);
iRunningByteTotal += len;
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)buffer.Length;
double dProgressPercentage = (dIndex / dTotal);
iProgressPercentage = (int)(dProgressPercentage);
if (iProgressPercentage > 100)
{
iProgressPercentage = 100;
}
bw.ReportProgress(iProgressPercentage);
}
}
但是,我的进度条没有更新。在搜索时,我被告知 UI 线程被阻塞,然后我认为可能将进度传递到循环之外就可以了。然后我改成这个
if (ftpSourceFilePath.Scheme == Uri.UriSchemeFtp)
{
FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(ftpSourceFilePath);
NetworkCredential objCredential = new NetworkCredential(userName, password);
objRequest.Credentials = objCredential;
objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
int len = 0;
int iProgressPercentage = 0;
FileStream objFS = new FileStream((cd+"\\VolareUpdate.rar"), FileMode.Create, FileAccess.Write, FileShare.Read);
while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
{
objFS.Write(buffer, 0, len);
iRunningByteTotal += len;
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)buffer.Length;
double dProgressPercentage = (dIndex / dTotal);
iProgressPercentage = (int)(dProgressPercentage);
if (iProgressPercentage > 100)
{
iProgressPercentage = 100;
}
// System.Threading.Thread.Sleep(2000);
iProgressPercentage++;
// SetText("F", true);
}
bw.ReportProgress(iProgressPercentage);
progressBar.Refresh();
}
然而仍然没有帮助。当我在 workerprogresschanged 事件中设置断点时,它会显示 progressbar.value 但不会更新。我尝试了progressbar.update(0,我也尝试在循环中将线程休眠一段时间仍然没有帮助。请任何建议/帮助将不胜感激。