StringBuilder.ToString() throw an 'Index out of range' Exception

Gerhard Powell picture Gerhard Powell · Sep 28, 2012 · Viewed 12.5k times · Source

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.

Answer

Gerhard Powell picture Gerhard Powell · Sep 28, 2012

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);
  }
}