我的问题是如果我有时在同一个字符串上使用多线程
字符串不会被替换。(我在记事本上写了这个,所以语法可能是
错误的)
使用 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);
}
}
}