跨线程操作对后台工作程序无效

时间:2016-11-03 08:20:25

标签: c# multithreading progress-bar backgroundworker

我希望这不会很难。

我尝试在填充gridview时实现这一点,我的进度条使用字幕样式。

这就是我现在所拥有的:

private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    progressBar1.Style = ProgressBarStyle.Marquee;
    progressBar1.MarqueeAnimationSpeed = 50;

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += bw_DoWork;
    bw.RunWorkerCompleted += bw_RunWorkerCompleted;
    bw.RunWorkerAsync();
} 

然后:

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    dt.Rows.Clear();
    fillData();
    Thread.Sleep(10000);
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    progressBar1.MarqueeAnimationSpeed = 0;
    progressBar1.Style = ProgressBarStyle.Blocks;
    progressBar1.Value = progressBar1.Minimum;

    button1.Enabled = true;
    MessageBox.Show("Done!");
}

但是这在这段代码的最后一行给了我一个交叉线程错误:

public void fillData()
{            
    OleDbDataAdapter adapter = new OleDbDataAdapter();
    OleDbCommand cmd;
    string sql = "CC_SP_ReadTags'" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text +"','','Timestamp ASC','TIMESTEP=30,2'";
    cmd = new OleDbCommand(sql, con);
    adapter.SelectCommand = cmd;
    adapter.Fill(dt);
    myGrid.DataSource = dt;           
}    

任何有关如何处理它的帮助都会非常感激,请考虑我还是新手。

感谢所有人。

0 个答案:

没有答案