Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the same string(StringBuilder) using multi-thread

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);
                }
            }
}
like image 788
Athiwat Chunlakhan Avatar asked May 23 '26 05:05

Athiwat Chunlakhan


1 Answers

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");
}
like image 176
Philippe Leybaert Avatar answered May 24 '26 17:05

Philippe Leybaert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!