我有一个带有以下代码的按钮
new Thread(() =>
{
DataTable table = Finish(txtTest.Text);
//dgwTest.DataSource = table
}).Start();
我想设置datagridview数据源,但我得到一个“交叉线程”异常。任何人都知道如何避免这种情况?
答案 0 :(得分:5)
string source = txtTest.Text;
new Thread(() =>
{
DataTable table = Finish(source);
dgwTest.Invoke ((Action) (() => dgwTest.DataSource = table));
}).Start();
答案 1 :(得分:0)
您需要在DataGridView
private delegate void SetDGVValueDelegate(DataTable table);
private void button1_Click(object sender, EventArgs e)
{
new Thread(() => {
DataTable table = Finish(txtTest.Text);
SetDGVValue(table);
}).Start();
}
private void SetDGVValue(DataTable table)
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(new SetDGVValueDelegate(SetDGVValue), table);
}
else
{
dataGridView1.DataSource = table;
}
}