Problem with background worker
Say I have the following class/Form (semi psuedo):
public partial class X : Form
{
private DataTable dt;
private BackgroundWorker bg;
public X()
{
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Columns.Add("C");
}
private void button_Click(...)
{
bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerAsync();
}
private void bg_DoWork(...)
{
// do some stuff
MagicMethod(parameters);
// doesnt work, how to fix开发者_StackOverflow社区 this?
dataGridView1.Invoke((Action)delegate { dataGridView1.DataSource = dt; });
}
private void MagicMethod(params)
{
// update a label, WORKS
label1.Invoke((Action) delegate { label1.Text = "somestuff" }
// do some stuff to fill the datatable
}
}
Ofcourse this is a distilled version, without the BackgroundWorker everything is sound, but since I want a more responsive UI I try to implement one. But the grid doesnt get updated by the worker (whereas the label does correctly). Any tips?
You may very well be causing an exception somewhere (probably inside MagicMethod) and because you don't handle the Bgw RunWorkerCompleted event you don't notice it.
So, add a RunWorkerCompleted event and check if e.Error != null
The completed event is also a convenient and safe place to process the results: dataGridView1.DataSource = dt;
See this MSDN example and pay attention to the if/else if/else pattern in the RunWorkerCompleted event.
精彩评论