-3

I'm trying to log some messages to a RichTextBox control. It logs the first 2 or 3, then throws the following error:

"Cross-thread operation not valid: Control 'txtLog' accessed from a thread other than the thread it was created on."

This is a very simple app that just does a single subscription. There was no attempt at threading.

Per another question I found on SO, I'm using a stringbuilder:

    public StringBuilder logtext = new StringBuilder();

Then I wanted to simplify things so I could just call log("this is a log message"):

    public void log(string txt)
    {
        logtext.Append(Environment.NewLine + txt);
        txtLog.Text = logtext.ToString();
    }

Like I said, it logs a few strings fine but then it tries to log the following:

"ConnectStatus: [1,\"Connected\",\"presence\"]"

that's when it throws the error. Here is the code which is returning that value:

pubnub.Subscribe<string>(
  chnl, 
  DisplayReturnMessage, 
  DisplayConnectStatusMessage, 
  DisplayErrorMessage
);

public void DisplayReturnMessage(string result)
{
    log(TimeStamp() + " Result: " + result);
}

And here is a ss of the debugger if it helps:

enter image description here

Please ignore the fact that TimeStamp() literally returns "H:mm:ss.ffff" right now :)

I was able to manually log("ConnectStatus: [1,\"Connected\",\"presence\"]") and it worked, so I don't think it's a string issue. The threading thing is really throwing me off.

THE JOATMON
  • 16,761
  • 34
  • 110
  • 200
  • Not a duplicate, he is actually using threading. I'm not (as far as I know ¯\\_(ツ)_/¯) threading or doing any type of invocation, which is mentioned all over that post. – THE JOATMON Aug 26 '16 at 17:14
  • 1
    I think it's a reasonable inference that `pubnub` is using threading. Are you aware of any known cases where .NET throws that exception erroneously, just for laughs? Who's more likely to have complete knowledge about whether or not there's a second thread: You, or the .NET runtime? – 15ee8f99-57ff-4f92-890c-b56153 Aug 26 '16 at 17:16

1 Answers1

0

Based on the duplicate question I modified my log() method:

    public void log(string txt)
    {
        logtext.Append(Environment.NewLine + txt);
        txtLog.Invoke(new Action(delegate { txtLog.Text = logtext.ToString(); }));
    }

Now it works.

THE JOATMON
  • 16,761
  • 34
  • 110
  • 200