我正在编写具有全局信号量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");
}
答案 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");
}