This question has already been answered:

Program: processes the text (counts words, etc.).

In the program: there is a method in which the line is assembled:

private void PrintResume() { strText.Append("Первая строка: " + int1 + Environment.NewLine); strText.Append("Вторая строка: " + int2 + Environment.NewLine); richTextBox2.Text += strText.ToString(); } 

And accordingly, richTextBox2 , which is inside tabPage6 .

It works fine, except if you switch the tab (there are several of them, with richTextBoxes and listviews). In this case, the program begins to swear that " попытка доступа к richTextBox2 не из того потока, в котором он был создан ." Moreover, if you switch to tabs from the listview, this does not happen.

What could be the problem?

Reported as a duplicate by Athari , DeKaNszn , fori1ton , VladD c # Apr 30 '15 at 8:08 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • There is something different here, at least in this formulation. Why would an error with threads appear only when switching tabs? - Pavel Mayorov

1 answer 1

The true cause of the problem, excluding Exception 's in the text, is difficult for me to call.
I advise you to try to bypass it using the following code:

 if (richTextBox2.InvokeRequired) richTextBox2.Invoke(new MethodInvoker(() => { richTextBox2.Text += strText.ToString(); })); else richTextBox2.Text += strText.ToString(); 

Instead

 richTextBox2.Text += strText.ToString(); 
  • new MethodInvoker makes sense to remove. - Qwertiy
  • @Qwertiy is not compiled without it. Is it really compiled? - Dmitry D.
  • Arguments in lambda add. (s, e) => - Qwertiy
  • @Qwertiy it does not help, of course. Please arm yourself with a compiler and try it yourself. - Dmitry D.
  • Sorry, (s, e) - I mixed it up with events. But the lambda must somehow be transmitted without wrapping. I'll check later. - Qwertiy