简体   繁体   English

锁定多线程

[英]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(). 那是我的代码,两个不同的线程调用方法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. 它进入ReceiveFromSwitch,锁定资源,第二个线程正在等待资源被释放。 A connection on the list is added, it steps into MethodX() and release the method ReceiveFromSwitch for a thread in the queue. 在列表上添加了一个连接,该连接进入MethodX()并为队列中的线程释放方法ReceiveFromSwitch。 The second one steps into the method. 第二步进入方法。 The count equals 1, so it shows message. 计数等于1,因此显示消息。

It doesn't work. 没用 It gives two messages "Whatever". 它给出两个消息“ 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. 发生的情况是,第一个线程进入并向列表添加连接,然后立即显示该消息,因为Count现在为1。第二个线程进入,并按预期显示了第二条消息。

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 . 第二个线程也会触发MethodX ,当它在10秒后执行时,它将尝试从已经为空的列表中删除索引0,从而导致ArgumentOutOfRangeException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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