C# Pogressbar 和后台工作者

单击按钮时,我的程序将执行以下操作: 程序将文件复制到临时文件夹并从临时文件夹中创建一个 zip 文件。被复制的文件的路径存储在一个数组中。只是为了让事情清楚:


// "files" has stored the paths


private void button2_Click(object sender, EventArgs e)

{

   foreach (var file in files)

   {

       File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));

   }

}

我想在我的表单中包含一个进度条,它提供有关所取得进展的反馈。对于每个复制的文件,进度条都应该移动。


我正在为如何以及在何处报告进展而苦苦挣扎。


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

{

        int steps = files.Length;


        for (int i = 0; i < steps; i++)

        {

            // Do something...

        }

}


繁星淼淼
浏览 156回答 3
3回答

慕运维8079593

您需要在ProgressChanged事件上注册一个处理程序,并调用ReportProgress(percentage)该DoWork方法。例子:class Program{&nbsp; &nbsp; private static BackgroundWorker _worker;&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _worker = new BackgroundWorker();&nbsp; &nbsp; &nbsp; &nbsp; _worker.DoWork += Worker_DoWork;&nbsp; &nbsp; &nbsp; &nbsp; _worker.ProgressChanged += Worker_ProgressChanged;&nbsp; &nbsp; &nbsp; &nbsp; _worker.WorkerReportsProgress = true;&nbsp; &nbsp; &nbsp; &nbsp; _worker.RunWorkerAsync();&nbsp; &nbsp; &nbsp; &nbsp; Console.ReadLine();&nbsp; &nbsp; }&nbsp; &nbsp; private static void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Progress is {0}", e.ProgressPercentage);&nbsp; &nbsp; }&nbsp; &nbsp; private static void Worker_DoWork(object sender, DoWorkEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var worker = (BackgroundWorker)sender;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 100; ++i)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; worker.ReportProgress(i); // Reporting progress in percent&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.Sleep(50);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

梵蒂冈之花

将MaximumProgressBar的属性设置为您的文件数。这样您就不必自己计算百分比。在复制文件的循环中,只需增加ValueProgressBar的属性即可。在UI线程中复制文件并在后台线程中更新ProgressBar是没有意义的,如果真的花费太长时间,则应该相反。

千万里不及你

我自己想通了:对于每个拥有数组并希望使用进度条和后台工作人员的人(可能有更好的方法):private void Button (object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; backgroundWorker1.RunWorkerAsync();&nbsp; &nbsp; }void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var files = Directory.GetFiles(startPath, "*" + filetype, SearchOption.AllDirectories);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int max = files.Length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int i = 0;&nbsp; &nbsp; &nbsp; &nbsp; foreach (var file in files)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundWorker1.ReportProgress((i * 100) / max);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP