I am facing an issue with updating DataGridView while each thread operates on different row, it all time crash.
Here is example of what I try to do, but honestly I don't know how to fix it.
Researched invoke method but doesn't work :(
private void threadingFunction()
{
int ThreadsNumber = dataGridView1.Rows.Count;
List<Task> tasks = new List<Task>();
for (int i = 0; i < ThreadsNumber; i++)
{
tasks.Add(Task.Factory.StartNew(() => myFunction(i)));
Thread.Sleep(1000);
}
Task.WaitAll(tasks.ToArray());
}
private void myFunction(int i)
{
doSomething()
dataGridView1[4, i].Value = "1";
doSomething();
dataGridView1[4, i].Value = "2";
doSomething();
Thread.Sleep(1000);
dataGridView1[4, i].Value = "3";
doSomething();
Thread.Sleep(1000);
dataGridView1[4, i].Value = "4";
doSomething();
Thread.Sleep(1000);
dataGridView1[4, i].Value = "5";
doSomething();
Thread.Sleep(1000);
dataGridView1[4, i].Value = "6";
}
Update
I figured out, when in same time thread1 update datagridview, and thread2 started same time want do same action take or fill datagrid view cell, it throw errors, "out of index", "error instance of object" etc. Anyone know how to fix this issue, because it crash my whole program.. and cant figure out how to correctly invoke implement to this .
here code I am testing:
private void threadingFunction()
{
int ThreadsNumber = dataGridView1.Rows.Count;
List<Task> tasks = new List<Task>();
for (int i = 0; i < ThreadsNumber - 1; i++)
{
tasks.Add(Task.Factory.StartNew(() => myFunction(i)));
Thread.Sleep(0);
}
Task.WaitAll(tasks.ToArray());
}
private void myFunction(int i)
{
var geg = dataGridView1[4, i].Value.ToString();
dataGridView1[5, i].Value = geg;
//dataGridView1[4, i].Value = "2";
//dataGridView1[4, i].Value = "3";
//dataGridView1[4, i].Value = "4";
//dataGridView1[4, i].Value = "5";
//dataGridView1[4, i].Value = "6";
}
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
backgroundWorker1.RunWorkerAsync();
}