【发布时间】:2010-01-22 12:57:02
【问题描述】:
我有一个包含多个数据成员的类:
public class Foo
{
List<int> intLst;
int Whatever;
HashTable<string> hshTable;
...
}
然后我在 Foo 中有一个函数,它接受两个 Foo 并将它们合并为一个新的 Foo。我也想让 Foo 类线程安全。下面的代码是最好的方法吗?
public Foo(Foo f)
{
lock(f)
{
foreach (int i in f.intLst)
{
this.intLst.Add(i)
}
//More complicated
}
}
public Foo Merge(Foo f1, Foo f2)
{
Foo fReturn = new Foo(f1);//Using the constructor above
lock(f2)
{
foreach (int i in f2.intLst)
{
fReturn.intLst.Add(i);
}
//More complicated merge code
}
return fReturn;
}
就这么简单吗?我应该改用监视器吗?我知道 lock 实现了监视器类,但也许还有一个原因。我还需要担心在上面的示例中处理死锁。
我觉得我需要 lock() f1 和 f2,因为如果 f2 在 f1 上的复制构造函数期间发生变化怎么办?
【问题讨论】:
-
顺便说一句,List
类型有 Union() 和 Concat() 方法...
标签: c# multithreading