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

Categories

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

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

1 Answer

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...