Click here to Skip to main content
15,881,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is a good example of the progressbar on it's own thread but where do I place my code that is actually performing the real work? Copying multiple files.

BackgroundWorker and ProgressBar demo[^]

What I have tried:

I put my code in the DoWork before the for loop but the progress bar does not update until my code finishes.

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Your background task goes here

    string sourceDirectory = @"N:\0000\Current_Project";
    string targetDirectory = @"C:\0000\Current_Project";

    Cursor.Current = Cursors.WaitCursor;
    Copy(sourceDirectory, targetDirectory);
    Cursor.Current = Cursors.Default;

    for (int i = 0; i <= 100; i++)
    {
        // Report progress to 'UI' thread
        backgroundWorker1.ReportProgress(i);
        // Simulate long task
        System.Threading.Thread.Sleep(100);
    }
}
Posted
Updated 2-Sep-22 4:49am
v2
Comments
Richard MacCutchan 1-Sep-22 14:08pm    
You put the copying code in the background worker.
Member 15754822 2-Sep-22 8:13am    
Could it be because I'm calling a method from the DoWork?
Copy(sourceDirectory, targetDirectory);

Background_DoWork is running in the background but it is still a sequentially executing chunk of code like any other method. It's doing exactly what you told it to in the order you told it:
1) Copy directory
2) update progress

You need to update the progress bar as you're copying the contents of the directory. You didn't post the contents of your Copy method so I'm just guessing how to update it. Something like

string[] fileList = Directory.GetFiles (sourceDir);
for (int i = 0; i < fileList.Length; i++)
{
    // copy fileList[i] to targetDir

    // !!! here is where you update the progress bar, each time you finish copying one file
    backgroundWorker1.ReportProgress(i * 100 / fileList.Length);
}


(edit: fixed the for loop exit test (was <=))
 
Share this answer
 
v2
Your code goes in the DoWork event, and uses the sender parameter to identify the specific worker. You then use that to call the ReportProgress method to signal to the main (UI) thread that it should update the ProgressBar.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900