[英]Cross-thread operation not valid c#
my problem is How can I assign a thread to a Control
. 我的问题是How can I assign a thread to a Control
。 I did this article but it didn't work for me. 我写了这篇文章,但对我没有用。
pls help me to find out where I'm making mistake. 请帮助我找出我在哪里犯错。 thx 谢谢
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();
}
}
}
my error is: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
我的错误是: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
If I don't use Task
in a right way. 如果我没有正确使用Task
。 pls give me a good article
. 请给我一篇好article
。 thank u 感谢你
You can only change UI using UI Thread. 您只能使用UI线程更改UI。
[updating datasource have effects on UI] [更新数据源会对UI产生影响]
Replace the line generating error with : 将产生错误的行替换为:
Action DoCrossThreadUIWork = () =>
{
dataGridView1.DataSource = Task.FromResult(customerContext.Select_CustomerGrp());
};
this.BeginInvoke(DoCrossThreadUIWork);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.