C# 当多个线程试图同时运行一个方法时,如何只执行一次;但是,队列中的其他线程应该等待此方法

C# 当多个线程试图同时运行一个方法时,如何只执行一次;但是,队列中的其他线程应该等待此方法,c#,multithreading,thread-safety,deadlock,race-condition,C#,Multithreading,Thread Safety,Deadlock,Race Condition,我在winforms应用程序中有一个TCP重新连接方法;多个线程尝试通过TCP发送/接收数据。如果发送数据时连接丢失,则调用重新连接(可以从多个线程调用)。但是,我不想多次执行重新连接。 为了实现这一点,我使用下面的代码-请让我知道这是一个好方法。 提前谢谢 public bool Reconnect(out bool wasLockedByOThers) { bool reconnected = wasLockedByOThers = false;

我在winforms应用程序中有一个TCP重新连接方法;多个线程尝试通过TCP发送/接收数据。如果发送数据时连接丢失,则调用重新连接(可以从多个线程调用)。但是,我不想多次执行重新连接。 为了实现这一点,我使用下面的代码-请让我知道这是一个好方法。 提前谢谢

    public bool Reconnect(out bool wasLockedByOThers)
    {
        bool reconnected = wasLockedByOThers = false;
        try
        {
             //check if the lock can be acquired immediately 
            if (!Monitor.TryEnter(m_ReconnectLock)) 
            {
                // if not, wait until the lock is acquired. If the lock is acquired here it means reconnect just happened so I'll just return without running it again. But the problem is I'll not know if the previous reconnect call resulted in true or false.
                Monitor.Enter(m_ReconnectLock);
                wasLockedByOThers = true;
            }
            else
            {
                reconnected = true; //reconnect logic
            }
        }
        catch (Exception ex)
        { 
            reconnected = false;
        }
        finally
        {
            Monitor.Exit(m_ReconnectLock);
        }
        return reconnected;
    }

您是否有任何锁定来确保您的tcp写入是原子的?你是用异步方法写的吗?就我个人而言,我只会使用
信号量lim
来确保只有一个任务写入或重新连接。它们是同步方法,但是读取(轮询)和写入数据可以并行进行-如果读卡器看到断开的连接,它会尝试重新连接;如果写入程序发现连接丢失,则尝试重新连接;可能导致潜在的竞争条件;