38

I would really appreciate someone help me resolving the following issue:

I am getting now and then the following exception:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: chunkLength

on stringBuilder.ToString().

What is strange is if I put stringBuilder.ToString() in the watch, it works perfectly.

Gerhard Powell
  • 5,965
  • 5
  • 48
  • 59
  • 16
    Is it possible that your StringBuilder is also being used by another thread? – Thomas Levesque Sep 28 '12 at 18:24
  • 1
    Could you provide the snippit that causes the exception including how string builder is built up? – deepee1 Sep 28 '12 at 18:25
  • The stringBuilder.AppendLine is called on an events. It is then displayed on the screen on a different thread. – Gerhard Powell Sep 28 '12 at 18:29
  • 3
    @GerhardPowell, that's probably the cause of your problem. StringBuilder is not thread-safe, it shouldn't be used concurrently from different threads. If you need to display it from a different thread, pass the result of ToString to the other thread, not the StringBuilder itself. – Thomas Levesque Sep 28 '12 at 18:35

1 Answers1

50

Look like it is a multi thread issue. I locked the thread to prevent multi access to the stringBuilder at the same time.

public void AddString(string s)
{
  lock(this.LockObject)
  {
     StringBuilder.AppendLine(s);
  }
} 
Gerhard Powell
  • 5,965
  • 5
  • 48
  • 59