Search code examples
c#multithreadingbackgroundworker

How to call Background progressChanged while getting data from method which returns collection


I have method which retrieves data. I am calling that method inside background worker DoWork. I wanted to display the progress on UI. How do I show the progress (time taken to execute method from 0 to 100) in percentage. SO that I can report progress using bgWorker_ProgressChanged

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    MyCollection = GetReportData();            
}

Solution

  • First, you have to specify that you want to be able to report progress:

    bgWorker.WorkerReportsProgress = true;
    

    Then, modify your DoWork event to actually report progress. You're currently getting all of your data at once, which doesn't lend itself well to showing progress as you're getting data.

    You'll need to break down your GetReportData() into manageable pieces.

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        var bg = (BackgroundWorker)sender;
    
        var myCollection = new List<SomeClass>();
    
        while(/* somehow test whether there's more data to get */)
        {
            myCollection.AddRange(GetSomeMoreReportData());
    
            bg.ReportProgress(0);  // or pass a valid "percentage" if you can calculate it
        }
    
        // Don't access the UI from a background thread.
        // The safest thing you can do is pass the final data to the RunWorkerCompleted event
        e.Result = myCollection;
    }
    
    void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // You're back in the UI thread, update your ProgressBar
    }
    
    void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        List<SomeClass> result = (List<SomeClass>)e.Result;
    
        // You're back in the UI thread, update your UI with the data
    }
    

    This is all pretty generic, and I've made some assumptions about your environment. Give this a try and modify it for your situation... if you play around with it a bit and get stuck, then post back here.