0

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

Iran_Girl
  • 439
  • 2
  • 11
  • 18
  • While I dont use Task, DataGrid fill. but when I use Task dont fill. what should i do?! sb help plz!!! if i did know, I never create a topic :( – Iran_Girl Apr 11 '14 at 15:32

1 Answers1

2

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);
Zein Makki
  • 29,485
  • 6
  • 52
  • 63