c #Asynchronous capture from a process output and display it in a RichTextBox
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."
I try to use this:
context.Post(new SendOrPostCallback(newMethod), (object)proba);
开发者_StackOverflow社区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.
You can use Control.InvokeRequired and MethodInvoker combination. See a similar post here: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b9e6c83e-e36b-4f99-893e-0b242f4f225c
精彩评论