-1

I have tried to find a solution to this problem but I did not find or did not know, I'm new at C#

I found a lot of solutions that talk about (invoke) but I did not know how to fix them on my code ,Everything if find is just a solution for label or textbox, If possible solve the problem

"System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'"

Error Message Image

            for (int i = 0; i <= len - 1; i++)
        {

            if (i % 3 == 0)
            {
                split = proxy[proxy_counter].Split(':');
                num.Rows.Add(numlist[i], 0, 0, split[0], split[1], split[2], split[3]);

                proxy_counter++;
            }
            else
            {
                num.Rows.Add(numlist[i], 0, 0, split[0], split[1], split[2], split[3]);
            }

        }
  • 2
    Possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – ProgrammingLlama Dec 15 '18 at 09:42
  • Every google hit about this error message says the same thing, you cannot access a control in a worker thread. In other words, you cannot use `num`, it is not thread-safe. You don't have to, all that your thread actually needs is a string. So pass it as an argument to the worker. – Hans Passant Dec 15 '18 at 09:44
  • 1
    The only thing that may be interesting to perform on a background thread is the actual reading of the file. All the rest is heavily interacting with UI and I would run it on the UI thread. – Klaus Gütter Dec 15 '18 at 09:46

1 Answers1

0

The problem is on the MessageBox.Show. You can't change UI from a background thread. in order to do that you need to Invoke (as you said) the MessageBox.Show from the Principal Thread.

Change your MessageBox line for (assuming that that piece of code is inside a Windows Form):

InvokeIfRequired(() =>
    {
        MessageBox.Show("You Enter Less Than 6 Numbers!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    });

private void InvokeIfRequired(Action method)
{
    if (this.InvokeRequired)
    {
        Invoke(method);
    }
}
Guido Zanon
  • 2,939
  • 26
  • 31