0

I'd like to update TextBox.Text in a thread but it doesn't work and I get this error (In French) :

System.InvalidOperationException : 'Opération inter-threads non valide : le contrôle 'TextBOX' a fait l'objet d'un accès à partir d'un thread autre que celui sur lequel il a été créé.'

In English (Google Translate) it looks like :

System.InvalidOperationException: 'Invalid inter-thread operation: The' TextBOX 'control has been accessed from a thread other than the one on which it was created.'

How can I do so ? Here is my code :

using System;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace Ace
{
    public partial class Checker : Form
    {

        public Checker()
        {
            InitializeComponent();
        }

        private void Checker_Load(object sender, EventArgs e)
        {
            status("Checking ...");
            check();
            status("Done !");
        }

        public void check()
        {
            int threads = 10;
            var lines = File.ReadLines("test.txt");
            Parallel.ForEach(lines, new ParallelOptions { MaxDegreeOfParallelism = threads }, line =>
            {
                TextBox.Text = TextBox.Text + line + "\n"; // THIS LINE
            });
        }
    }
}

Thanks in advance.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136

1 Answers1

0

You must call Invoke() on the component, when attempting to modify it from another thread than the UI thread.

Change:

TextBox.Text = TextBox.Text + line + "\n"; // THIS LINE

To:

TextBox.Invoke((Delegate)(() =>
{
    TextBox.Text = TextBox.Text + line + "\n";
})));

Also you can change:

TextBox.Text = TextBox.Text + line + "\n";

To:

TextBox.Text += line + "\n";

I want to warn you about your code though. It's not thread-safe and race-conditions can happen.

Bauss
  • 2,767
  • 24
  • 28