Reputation: 459
my problem is 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.
If I don't use Task
in a right way. pls give me a good article
. thank u
Upvotes: 0
Views: 3193
Reputation: 30022
You can only change UI using UI Thread.
[updating datasource have effects on UI]
Replace the line generating error with :
Action DoCrossThreadUIWork = () =>
{
dataGridView1.DataSource = Task.FromResult(customerContext.Select_CustomerGrp());
};
this.BeginInvoke(DoCrossThreadUIWork);
Upvotes: 2