Search code examples
c#backgroundworker

Can we call method in DoWork event?


I am exporting a Data Table to excel file using background worker. And I wanted to show the export progress using progress bar. Do we have to write the exporting code in Do Work event or can we call a method, which is present in other class. In my code I tried calling different method. But its not working. Below is the sample code.

public MainWindow()
{
    InitializeComponent();
    property = new Property();
    this.DataContext = property;
    worker.WorkerReportsProgress = true;
    worker.DoWork += worker_DoWork;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        System.Windows.Forms.MessageBox.Show(e.Error.Message);
    }
    else
    {
        System.Windows.Forms.MessageBox.Show("Exported Successfully");
    }
}

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    pbStatus.Value = e.ProgressPercentage;
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    Export export = new Export();
    export.GenerateExcelFile();
}

Solution

  • You need to call worker.ReportProgress from worker_DoWork with a valid progress value

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        worker.ReportProgress(0);
        // Some job 
        worker.ReportProgress(10); 
        // ...
        // Finish
        worker.ReportProgress(100);
    }
    

    I'm not sure how you are generating report. Further I'm supposing your pbStatus has Minimum="0" and Maximum="100". You can after exporting each row report progress something like that.

    worker.ReportProgress(currentRow * 100.0 / totalRows);
    

    You also set your progress bar intermediate if you are not sure how to calculate that by setting progress.IsIndeterminate to true

    pbStatus.IsIndeterminate = true;