简体   繁体   中英

Cross-thread operation not valid c#

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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