C#: Thread safe richtextbox event logging method?
<p>I have a method that is meant to display output on a RichTextBox in a form.</p>

<pre><code>    public void LogTextEvent(RichTextBox TextEventLog, Color TextColor, string EventText)
    {
        string nDateTime = DateTime.Now.ToString("hh:mm:ss tt") + " - ";

        // color text.
        TextEventLog.SelectionStart = TextEventLog.Text.Length;
        TextEventLog.SelectionColor = TextColor;

        // newline if first line, append if else.
        if (TextEventLog.Lines.Length == 0)
        {
            TextEventLog.AppendText(nDateTime + EventText);
            TextEventLog.ScrollToCaret();
            TextEventLog.AppendText(System.Environment.NewLine);
        }
        else
        {
            TextEventLog.AppendText(nDateTime + EventText + System.Environment.NewLine);
            TextEventLog.ScrollToCaret();
        }
    }
</code></pre>

<p>The problem arises when I call LogEventText() from another method running inside a thread:</p>

<pre><code>            Thread thListening = new Thread(new ThreadStart(StartListening));
            thListening.Start();
</code></pre>

<p>Inside the StartListening method (it is a thread created that handles new tcp sockets to be created for clients on a main listening socket for a small http server), I make use of LogTextEvent to log some data, but I receive an InvalidOperationException was unhandled error in the LogTextEvent method at the 2nd line, TextEventLog.SelectionStart = TextEventLog.Text.Length;</p>

<p>The error reads, Cross-thread operation not valid: Control 'rchEventLog' accessed from a thread other than the thread it was created on.</p>

<p>Can anyone help break down what's going on, why, and how the error could be fixed?</p>
