如何检查信号灯是否处于等待状态?

时间:2018-08-07 12:31:45

标签: c# .net synchronization semaphore

我正在编写具有全局信号量ServerStatusFileSemaphore的代码。我只想在try内成功等待信号量后才在catch块中释放该信号量。

我的代码是

/*Initialization*/
Semaphore ServerStatusFileSemaphore = new Semaphore(1, 1, "ServerStatusFileSemaphore");

/*Use inside function*/
//Location is file directory and is initialized.
try
{
    ServerStatusFileSemaphore.WaitOne();
    using (StreamWriter SW = new StreamWriter(Location, true))
    {
        SW.WriteLine(Message);
    }
    ServerStatusFileSemaphore.Release(1);
}
catch (Exception)
{
    ServerStatusFileSemaphore.Release(1);
    Console.WriteLine("Problem inside AppendToStatusFile");
}

2 个答案:

答案 0 :(得分:1)

WaitOne调用放在之前 try,然后将单个Release调用放入finally块中(除掉其他的)。这样,您仅在成功获取信号量后才输入try/finally,并且始终将其释放。

答案 1 :(得分:1)

根据MSDN,WaitOne()返回

  

如果当前实例接收到信号,则为true。如果当前实例从未发出信号,则WaitOne永远不会返回

因此,您可以在返回后尝试/最终开始处理它。

    try
    {
        // do whatever before semaphore needed
        ServerStatusFileSemaphore.WaitOne();
        try
        {
            using (StreamWriter SW = new StreamWriter(Location, true))
            {
                SW.WriteLine(Message);
            }
            // do whatever while you have the semaphore
        }
        finally
        {
            ServerStatusFileSemaphore.Release(1);
        }
        // do whatever after semaphore released
    }
    catch (Exception)
    {
        // No need to release in here, it was either never acquired or already released
        Console.WriteLine("Problem inside AppendToStatusFile");
    }