Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

c# - How to show progress bar in windows application?

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 in arraylist. I want to invoke progress bar method for this file processing but its not working.

Any help

PFB my code snippet:

public void TraverseSource()
{
    string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);

    var allFiles = new ArrayList();
    var length = allFiles.Count;
    foreach (string item in allFiles1)
    {
        if (!item.Substring(item.Length - 6).Equals("MD.xml"))
        {
            allFiles.Add(item);

            // Here i want to invoke progress bar which is in form
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...