繁体   English   中英

跨线程操作无效C#

[英]Cross-thread operation not valid c#

我的问题是How can I assign a thread to a Control 我写了这篇文章,但对我没有用。

请帮助我找出我在哪里犯错。 谢谢

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 感谢你

您只能使用UI线程更改UI。
[更新数据源会对UI产生影响]

将产生错误的行替换为:

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

this.BeginInvoke(DoCrossThreadUIWork);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM