gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:35:23 28 4
gpt4 key购买 nike

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

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

错误)

使用 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")
}
}
}

现在有时某些元素不会被替换。所以我的解决方案是在不同的地方调用 container.Replace

方法和做一个“锁”是有效的,但它是正确的方法吗?

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

最佳答案

您应该锁定 StringBuilder 对象本身(在替换函数内):

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

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

static object _stringLock = new object();

...

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

关于c# - 使用多线程访问相同的字符串(StringBuilder),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1268446/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com