跨线程操作无效c#

时间:2014-04-11 14:50:42

标签: c# controls task invoke

我的问题是How can I assign a thread to a Control。我做了this article,但它对我没用。

请帮助我找出我犯错误的地方。 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();
        }
     }


    }

我的错误是: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

如果我没有以正确的方式使用Task。请给我一个好的article。谢谢你

1 个答案:

答案 0 :(得分:2)

您只能使用UI主题更改UI。
 [更新数据源对UI有影响]

将行生成错误替换为:

Action DoCrossThreadUIWork = () =>
{
     dataGridView1.DataSource = Task.FromResult(customerContext.Select_CustomerGrp());
};

this.BeginInvoke(DoCrossThreadUIWork);