Cross-thread operation Error

Dec 6, 2011 at 9:09 PM

I found problems running the code in VS2010 debugger,
"Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on."
OutputWindowControl.cs line 21

This was my solution, hope it helps.

 
public class FindAndReplace : System.Windows.Forms.Form 
{
        delegate void WriteRealTimeLineCallback(string text);
        delegate void SetButtonCallback(bool isEnabled);
.
.
.

private void EnableButtons(bool isEnable){
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
   if (this.buttonExit.InvokeRequired){
       SetButtonCallback d = new SetButtonCallback(EnableButtons);
       this.Invoke(d, new object[] { isEnable });
   }
   else {
       this.buttonExit.Enabled = isEnable;
       this.buttonStart.Enabled = isEnable;
       this.buttonStop.Enabled = !isEnable;
       this.pictureBox1.Visible = !isEnable;
   }
}

protected void SetText(string text)
{
    if (this.richTextBox1.InvokeRequired)
    {
        WriteRealTimeLineCallback d = new WriteRealTimeLineCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
         this.richTextBox1.OutputText(text);
    }
}


protected void WriteRealTimeLine(string message, string source, Exception ex)
{
    if ( message.Length == 0 )
    {
        SetText("");
        return;
    }
    string LineToRealTime;
    DateTime TimeStamp = DateTime.Now;

    m_Logger.Write(message, source, ex);
    if ( ex == null )
    {
        LineToRealTime = String.Format(@"{0}, {1} {2} ", TimeStamp.ToShortDateString(), TimeStamp.ToShortTimeString(), message);
    }
    else
    {
        Exception ex1 = ex;
        while (ex1 != null )
        {
            message += ex1.Message + "; ";
            ex1 = ex1.InnerException;
        }

        LineToRealTime = String.Format(@"{0}, {1}: ERROR: {2} ", TimeStamp.ToShortDateString(), TimeStamp.ToShortTimeString(), message);
    }
    SetText(LineToRealTime);
}
Coordinator
Dec 8, 2011 at 6:17 PM

Thanks for posting!

Anyone else had this problem? If so, please post here, if lot's of people are having it I'll probably take the time to update the code.

@melmes, if you'd like to update the code let me know, I'll invite you to be a contributor on this project.

Coordinator
Feb 1, 2013 at 5:28 PM
Fixed that,

Please check version 1.0.17 - different installers for sp2007 and sp2010.

Please report if you have trouble with it, or give a good word / rate if it does what you need!