I have a richTextBoxLog which is public and static.

After I declare it, I start a new thread which initializes new variable named proba. richTextBoxLog should get the value from proba.

The problem is, proba needs time to be initialized, and I want richTextBoxLog to initialize while proba is initializing.

I want to write something like:
richTextBoxLogFile.richTextBoxLog.Text += proba;
But, when I write it in the method which is called by the previously mentioned thread, I get an exception: "Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."

Can I write something like this: stop the thread, then initialize richTextBoxLog, then start the thread again, then stop it, and the same continues while initializing richTextBoxLog ends.

You need to Invoke a method to the UI thread to make changes to Controls and Components.
Something like this:

// proba initialisation thread method
void InitProba()
{
	// initialise proba
	proba = "proba Initialised.";
	// add proba to log
	richTextBoxLog.Invoke(new Action(() => richTextBoxLog.Text += proba));
}

Edited 5 Years Ago by nick.crane: n/a

I have a `richTextBoxLog` which is public and static.

After I declare it, I start a new thread which initializes new variable named `proba`. `richTextBoxLog` should get the value from `proba`.

The problem is, `proba` needs time to be initialized, and I want `richTextBoxLog` to initialize while `proba` is initializing.

I want to write something like:

richTextBoxLogFile.richTextBoxLog.Text += proba;

But, when I write it in the method which is called by the previously mentioned thread, I get an exception: `"Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."`

Can I write something like this: stop the thread, then initialize `richTextBoxLog`, then start the thread again, then stop it, and the same continues while initializing `richTextBoxLog` ends.


Edit: I try to use this:

context.Post(new SendOrPostCallback(newMethod), (object)proba);

where context is the context of the main thread and newMethod initializes the value of richTextBoxLog. However, this call is in the method which is started by the new thread, in a while loop:

while (-1 != (ch = _reader.Read()))
            {
                Console.Write((char)ch);
                proba += ((char)ch).ToString();
                context.Post(new SendOrPostCallback(newMethod), (object)proba);                
            }
            _complete.Set();
        }

The problem I have now is that I want newMethod to be called every time when I enter in the while loop. But, what's happening is: the while loop finishes and after that newMethod is entered about thousand times.

This article has been dead for over six months. Start a new discussion instead.