3 回答
TA贡献1876条经验 获得超5个赞
您需要在ProgressChanged事件上注册一个处理程序,并调用ReportProgress(percentage)该DoWork方法。
例子:
class Program
{
private static BackgroundWorker _worker;
static void Main(string[] args)
{
_worker = new BackgroundWorker();
_worker.DoWork += Worker_DoWork;
_worker.ProgressChanged += Worker_ProgressChanged;
_worker.WorkerReportsProgress = true;
_worker.RunWorkerAsync();
Console.ReadLine();
}
private static void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Progress is {0}", e.ProgressPercentage);
}
private static void Worker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
for (int i = 0; i < 100; ++i)
{
worker.ReportProgress(i); // Reporting progress in percent
Thread.Sleep(50);
}
}
}
TA贡献1900条经验 获得超5个赞
将
Maximum
ProgressBar的属性设置为您的文件数。这样您就不必自己计算百分比。在复制文件的循环中,只需增加
Value
ProgressBar的属性即可。在UI线程中复制文件并在后台线程中更新ProgressBar是没有意义的,如果真的花费太长时间,则应该相反。
TA贡献1784条经验 获得超9个赞
我自己想通了:对于每个拥有数组并希望使用进度条和后台工作人员的人(可能有更好的方法):
private void Button (object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var files = Directory.GetFiles(startPath, "*" + filetype, SearchOption.AllDirectories);
int max = files.Length;
int i = 0;
foreach (var file in files)
{
File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));
backgroundWorker1.ReportProgress((i * 100) / max);
i++;
}
}
- 3 回答
- 0 关注
- 155 浏览
添加回答
举报