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
Asked
Active
Viewed 3,857 times
2 Answers
3
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;
}

Vivek
- 16,360
- 5
- 30
- 37
1
You cannot access GUI controls from a background thread without doing an invoke().
I suspect this is your problem, if not you may need to provide some code of the part that is causing the problem.
For more information see:
- MSDN - InvokeRequired
- MSDN - Invoke(...)]
- StackOverflow question - How to update GUI from another thread in C#?
If you wrap the code in your background worker in a Try/Catch block, or change your visual studio settings to display all exceptions you will see an exception that explains what is going wrong.

Community
- 1
- 1

Simon P Stevens
- 27,303
- 5
- 81
- 107