How to show progress bar in windows application?

前端 未结 1 1403
萌比男神i
萌比男神i 2020-12-21 12:34

I am working on a windows application using c#.

I have a form and a class having all methods .

I have a method in class in which i am processing some files i

1条回答
  •  无人及你
    2020-12-21 13:16

    You'll want to use a BackgroundWorker component, in which the DoWork handler contains your actual work (the string[] allFiles1 part and beyond). It'll look something like this:

    public void TraverseSource()
    {
        // create the BackgroundWorker
        var worker = new BackgroundWorker
                           {
                              WorkerReportsProgress = true
                           };
    
        // assign a delegate to the DoWork event, which is raised when `RunWorkerAsync` is called. this is where your actual work should be done
        worker.DoWork += (sender, args) => {
           string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);
    
            var allFiles = new ArrayList();
    
            foreach (var i = 0; i < allFiles1.Length; i++)
            {
                if (!item.Substring(item.Length - 6).Equals("MD.xml"))
                {
                    allFiles.Add(item);
                    // notifies the worker that progress has changed
                    worker.ReportProgress(i/allFiles.Length*100);
                }
            }
        };
        // assign a delegate that is raised when `ReportProgress` is called. this delegate is invoked on the original thread, so you can safely update a WinForms control
        worker.ProgressChanged += (sender, args) => {
           progressBar1.Value = args.ProgressPercentage;
        };
    
        // OK, now actually start doing work
        worker.RunWorkerAsync();
    
    }
    

    0 讨论(0)
提交回复
热议问题