0
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?

3
  • Silly question but are the two threads calling the method on the same instance of Port? Because the list is not static. Commented Dec 8, 2013 at 16:04
  • Yes. it is the same instance. Commented Dec 8, 2013 at 16:09
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Dec 8, 2013 at 16:57

1 Answer 1

1

You forgot an else.

if(listOfConnections.Count == 0) listOfConnections.Add(new Connection());
else if(listOfConnections.Count == 1) MessageBox.Show("Whatever");

//or better yet
if (listOfConnections.Any())
{ 
    MessageBox.Show("Whatever");
}
else
{
    listOfConnections.Add(new Connection());
}

What's happening is the first thread enters and adds a connection to the list, and then immediately shows the message because the Count is now 1. The second thread enters, and as expected, shows the second message.

There is another problem with your code. The second thread will also trigger MethodX, and when it executes after 10 seconds, it will try to remove index 0 from an already empty list, causing an ArgumentOutOfRangeException.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, however it was just an example based on much longer code. The solution was deeper. Locker was doing great, but I was so confused that I suspected my incompetence was a reason of not working properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.