我有幾個數據成員的類:C#嵌套同步
public class Foo
{
List<int> intLst;
int Whatever;
HashTable<string> hshTable;
...
}
我再有內美孚的功能,它有兩個FOOS並將它們合併成一個新的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;
}
這是簡單的嗎?我應該使用監視器嗎?我知道鎖實現了監視器類,但是可能還有一個原因。我也需要擔心在上面的示例中處理死鎖。
我覺得我需要鎖定()f1和f2,因爲如果f2在f1上的複製構造函數期間發生了變化?
順便說一句,列表類型有Union()和Concat()方法... –
2010-01-22 04:35:28