I have a class with several data members:
public class Foo
{
List<int> intLst;
int Whatever;
HashTable<string> hshTable;
...
}
I then have a function within Foo that takes two Foos and merges them into a new Foo. I would like to make the Foo class thread safe too. Is the below code the best way to do this?
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;
}
Is it that simple? Should I use Monitors instead? I know lock implements the monitor class, but is there perhaps still a reason. Also do I need to worry about handling deadlock in my above sample.
I feel like a I need to lock() both f1 and f2 because what if f2 changes during the copy constructor on f1?