class Port
{
static readonly object locker = new object();
List<Connection> listOfConnections = new List<Connection>
public void MethodX()
{
Thread.Sleep(10000);
lock(locker)
{
listOfConnections.RemoveAt(0);
}
}
public void ReceiveFromSwitch()
{
lock(locker)
{
if(listOfConnections.Count == 0) listOfConnections.Add(new Connection());
if(listOfConnections.Count == 1) MessageBox.Show("Whatever");
new Thread(()=>MetohodX()).Start();
}
}
}
That's my code, two different threads call the method ReceiveFromSwitch(). My objective is to be given a messagebox "Whatever". One thread starts first. It steps into ReceiveFromSwitch, locks the resource and the second thread is waiting for the resource to be released. A connection on the list is added, it steps into MethodX() and release the method ReceiveFromSwitch for a thread in the queue. The second one steps into the method. The count equals 1, so it shows message.
It doesn't work. It gives two messages "Whatever". How can i fix it?
Port? Because the list is not static.