使用多线程访问相同的字符串(StringBuilder)

Ath*_*han 0 c# string stringbuilder

我的问题是,如果我有时在同一个字符串上使用多线程

字符串不会被替换.(我在记事本上写了这个,所以语法可能是

错误)

使用System.Thread ...其他的课程

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")
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在有时某些元素不会被取代.所以我对此的解决方案是调用container.Replace

方法并做一个"锁定"哪个有效,但这是正确的方法吗?

private class ModiflyString
{
        public void Do(string x, string y)
            {
                lock (this)
                {
                    fileInput.Replace(x, y);
                }
            }
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*ert 5

你应该锁定StringBuilder对象本身(在replace函数内):

lock (container)
{
   container.Replace("this", "With this");
}
Run Code Online (Sandbox Code Playgroud)

或创建一个单独的锁对象:

static object _stringLock = new object();

...

lock(stringLock)
{
    container.Replace("this", "With this");
}
Run Code Online (Sandbox Code Playgroud)