简体   繁体   中英

Lock in multi-threading

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM