Accessing the same string(StringBuilder) using multi-thread

c#, string, stringbuilder

Solution

You should lock the StringBuilder object itself (inside the replace functions):

lock (container)
{
   container.Replace("this", "With this");
}

or create a separate lock object:

static object _stringLock = new object();

...

lock(stringLock)
{
    container.Replace("this", "With this");
}

Problem

My problem is if I use multi-thread on the same string sometime the string won't get replace.(I wrote this on notepad so syntax may be wrong) using System.Thread ... Others ofcourse ``` class .... { private static StringBuild container = new StringBuilder(); static void Main(...) { container.Append(Read From File(Kind of long)); Thread thread1 = new Thread(Function1); Thread thread2 = new Thread(Function2); thread1.Start(); thread2.Start(); //Print out container } static void Function1 { //Do calculation and stuff to get the Array for the foreach foreach (.......Long loop........) { container.Replace("this", "With this") } } //Same goes for function but replacing different things. static void Function2 { //Do calculation and stuff to get the Array for the foreach foreach (.......Long loop........) { container.Replace("this", "With this") } } } ``` Now sometime some element does not get replace. So my solution to this is calling container.Replace on a different method and do a "lock" which work but is it the right way? ``` private class ModiflyString { public void Do(string x, string y) { lock (this) { fileInput.Replace(x, y); } } } ```

Original source