Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with background Worker and Data Table

Tags:

c#

Hi all I have a BAckground worker and a Datatable. I have a timer also . I am filling the data table in timer and In Backgroundworker_Progress changed I am assigining it to my DataGrid as my DataSource. But even after the process has been completed . My Background worker is not getting Completed .Due to which my application crashes.This happens only when I launch my exe directly

like image 932
subbu Avatar asked Mar 13 '26 01:03

subbu


1 Answers

I agree with @Simon. Paste some code so that we understand what might be wrong. Also, why are you using timer for?

Don't assign the DataTable in ProgressChanged event. Do it in RunWorkerCompleted event. Here is what I think you should do:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        e.Result = GetTableData();
    }
    catch (Exception ex)
    {
        e.Result = ex;
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // only display progress, do not assign it to grid
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Result is DataTable)
    {
       dataGridView1.DataSource = e.Result as DataTable;
    }
    else if (e.Result is Exception)
    {
    }
}

private DataTable GetTableData()
{
    DataTable table = new DataTable();
    for (int i = 0; i < NumOfRows; i++)
    {
        //... fill data here
        backgroundWorker1.ReportProgress(i * 100F / NumOfRows);
    }
    return table;
}
like image 195
Vivek Avatar answered Mar 15 '26 14:03

Vivek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!