0

I started my thread once again (old: DataGridView Multithread update crash) and tested implement invoke from this thread: (How do I update the GUI from another thread?), but still face weird issue:

Start multithread update with 0 thread sleep, and I face this issue:

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(() => Update(i)));
                Thread.Sleep(0);
            }

            Task.WaitAll(tasks.ToArray());
        }

void Update(int i)
        {
            BeginInvoke((Action)delegate ()
            {
                dataGridView1[4, i].Value = "heheh";
            });
        }

result image: result image thread sleep 0

and with thread sleep 1 ms it work fine

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(() => Update(i)));
                Thread.Sleep(1);
            }

            Task.WaitAll(tasks.ToArray());
        }

void Update(int i)
        {
            BeginInvoke((Action)delegate ()
            {
                dataGridView1[4, i].Value = "heheh";
            });
        }

thread sleep 1ms working fine

So I have code longer then this which update datagrid and take data from datagrid, and sometimes work without crash but sometimes it hit this issue and not update properly, or push errors (out of index), but I think invoke prevent push errors, it will just skip the value I want add or take.. but finally it will crash program or wont work properly. Anyone have idea how to put to queque refresh or taking data, and wait till if finish refresh gui?

  • Your lambe expression `() => Update(i)` will capture the variable `i` and when `Update(i)` is called whatever value there is in the variable i at that time will be used. Create a new variable `var col = i;` in the for loop and pass this to Update. – Klaus Gütter Apr 29 '21 at 11:04
  • Does this answer your question? [Is there a reason for C#'s reuse of the variable in a foreach?](https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach) – Klaus Gütter Apr 29 '21 at 11:06
  • First solution looks like working, even without invoke lol I will test on my end program and will let you know, but thanks a lot!! – Adult Marketing Apr 29 '21 at 13:07
  • I still got issues with main program, but there is much code, so can be other thing, as it show weird datagrid error dialog messagebox – Adult Marketing Apr 29 '21 at 15:25

0 Answers0