snur
snur

Reputation: 23

Multiple threading with datagridview

I created 2 data grid view on the form application. I filled both of the columns 0 to 100. I want to fill both of grid view's raws at the same time. In order to make filling raws I created two threads and I used Invoke methods to solve cross thread exception ;

public void thread1()
    {        dataGridView1.BeginInvoke(new Action(delegate ()
        {
            a = 0;

            dataGridView1.Rows.Add(20);
            for (int i = 0; i < 100; i++)
            {
                dataGridView1.Rows[a].Cells[0].Value = i;
                dataGridView1.Rows[a].Cells[1].Value = i + 1;
                dataGridView1.Rows[a].Cells[2].Value = i + 2;
                dataGridView1.Rows[a].Cells[3].Value = i + 3;
                dataGridView1.Rows[a].Cells[4].Value = i + 4;

                if (i % 5 == 0) { a++; }
                dataGridView1.Refresh();
            }
        }));

    }

But when I call the threads on the main program with Parallel.Invoke or Task Parallel Library data grid views value's fillings working sequantial.

I wonder how can I make them parallelize??

Upvotes: 2

Views: 3363

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You should not put time-consuming tasks in Control.Invoke code blocks because it will run in UI thread and makes the UI thread busy and makes your threading useless. So just put UI-reladet code in Invoke action.

You can use Task.Run to fill each DataGridView this way:

private void button1_Click(object sender, EventArgs e)
{
    Task.Run(() =>
    {
        //Define DataTable
        var table = new DataTable();
        table.Columns.Add("Column 1", typeof(int));

        //Fill DataTable
        for (int i = 0; i < 100000; i++)
            table.Rows.Add(new object[] { i });

        //Set DataSource
        dataGridView1.Invoke(new Action(() => { dataGridView1.DataSource = table; }));
    });
}

You can have similar Task.Run code blocks in button1_Click event handler to fill other DataGridView controls as well.

You can use either of these options:

  • Task.Run(()=>{ /* something */ });
  • new Thread(new ThreadStart(() => { /* something */ })).Start();

Upvotes: 1

Related Questions