I am sure this question would have been asked a lot of times, but I want to be clear of this concept.
Recently I came across a bug when two threads were accessing the same list in two different functions. In what scenarios can that cause problems if I don't have the proper locking? Even though I have a lock in the second function and the two threads are not related, they are manipulating the same list. One is adding and one is swapping with an empty list. Under what circumstances will it catch an exception? Please help.
PseudoCode:
List<SomeClass> list=new List<SomeClass>();
object mutex=new object();
Thread 1 accesses this function and modifies the list:
public void Manipulate()
{
//some operation
list.add(new SomeClass());
}
Thread 2 access this function and clears the list:
public void SwapList()
{
List<SomeClass> cls=new List<SomeClass>();
try
{
while(Thread2.isAlive)
{
//some operation
if(list.Count()>0)
{
lock(mutex)
{
swap(ref list,ref cls)
}
}
}
}
catch(exception ex)
{
}
}
public void swap(List<SomeClass> a, List<SomeClass> b)
{
List<SomeClass> temp=a;
a=b;
b=temp;
}