我的问题是How can I assign a thread to a Control
。我做了this article,但它对我没用。
private void frm_customerGrp_Load(object sender, EventArgs e)
{
customerContext = new Customer.CustomerEntities();
Task T_ref = Task.Factory.StartNew(() => refreshDataGridView());
if (T_ref.IsCompleted )
{
MessageBox.Show("hi");
}
}
delegate void Delegate_GridView();
void refreshDataGridView()
{
if (dataGridView1.InvokeRequired )
{
this.Invoke(new Delegate_GridView(refreshDataGridView));
// I have error at this line
dataGridView1.DataSource = Task.FromResult( customerContext.Select_CustomerGrp());
}
else
{
dataGridView1.DataSource = customerContext.Select_CustomerGrp();
}
}
}
我的错误是:
Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
如果我没有以正确的方式使用Task
。请给我一个好的article
。谢谢你
答案 0 :(得分:2)
您只能使用UI主题更改UI。
[更新数据源对UI有影响]
将行生成错误替换为:
Action DoCrossThreadUIWork = () =>
{
dataGridView1.DataSource = Task.FromResult(customerContext.Select_CustomerGrp());
};
this.BeginInvoke(DoCrossThreadUIWork);