我的问题是,如果我使用多线程上相同的字符串有时访问使用多线程相同的字符串(StringBuilder)对
字符串将不会进行更换。(我写了这个记事本上这样的语法可能
使用错误)
System.Thread ...其他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")
}
}
}
现在有时一些元素没有得到更换。 所以我的解决方案是调用container.Replace在不同的
方法,并做一个“锁”哪个工作,但它是正确的方式?
private class ModiflyString
{
public void Do(string x, string y)
{
lock (this)
{
fileInput.Replace(x, y);
}
}
}
我从来没有想过锁定stringbuilder本身,非常好。谢谢, – 2009-08-12 20:26:08
菲尔的第二个例子就是当我提到一个“虚拟”对象时所指的。然而,我认为他第一个锁定容器的例子是他们中最好的。由于容器表示线程之间共享的数据,因此您需要锁定该数据。如果您使用我的示例,则存在以下问题:如果您的线程尝试为完全独立的容器调用ModifyString.Do,则它们将相互阻塞,即使它们所使用的容器完全不同。所以你会伤害表现。所以我的例子实际上是一个糟糕的实现。 – AaronLS 2009-08-12 20:28:39
感谢@arronls现在我的程序正在工作:) – 2009-08-12 20:39:29