-1

i developed a C# application. while running that i switch to another window in my system then application went in to not responding mode but back ground process is running.. I have a progressBar in that application. i need to see the status,how far it is complete..

            progressBar1.Visible = true;
            progressBar1.Maximum = dt.Rows.Count;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    -----
                    ----
                    -----
                    progressBar1.Value = i;
                    if (progressBar1.Value == progressBar1.Maximum - 1)
                    {
                        MessageBox.Show("Task completed");
                        progressBar1.Visible = false;
                    }

                }
             }
MX D
  • 2,453
  • 4
  • 35
  • 47

1 Answers1

2

the for loop is freezing your UI thread, this is why the application freezes as the UI cannot be redrawn while you are working inside the for loop. I suggest offloading your work to another thread and using a background Worker as so:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (worker, result) =>
{
    int progress = 0;

    //DTRowCount CANNOT be anything UI based here
    // this thread cannot interact with the UI
    if (DTRowCount > 0)
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            progress = i;

            -----
            ---- //do some operation, DO NOT INTERACT WITH THE UI
            -----

            (worker as BackgroundWorker).ReportProgress(progress); 
        }
     }
};

worker.ProgressChanged += (s,e) => 
{
    //here we can update the UI
    progressBar1.Value = e.ProgressPercentage
};
worker.RunWorkerCompleted += (s, e) =>
{
    MessageBox.Show("Task completed");
                        progressBar1.Visible = false;
};

worker.RunWorkAsync();

What I am aiming for here is to offload this loop into another thread, This will allow your application to continue with the Windows Message pump and remain responsive to the user. The Worker loops through and does what it needs todo on another thread, this CANNOT interact with the UI or WindowForms (which i assume your using) will throw and error.

The Worker returns to the main thread with the progress report, as per the worker.ProgressChanged event, from here you CAN access the UI and change the progress bar value.

When the worker has finished it will callback to WorkerThread.RunWorkerCompleted and again you can manipulate the UI from here.

Edit: Code, WorkerThread.RunWorkerCompleted to worker.RunWorkerCompleted

Alex Anderson
  • 840
  • 5
  • 11