Search code examples
c#exceptiontostringstringbuilder

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


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.


Solution

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