【发布时间】:2019-10-18 21:19:34
【问题描述】:
我正在运行一些非线程安全的单例代码,并且需要一些时间才能运行。 它偶尔会被多个用户同时调用,所以我使用 Monitor 来处理处理请求排队,如下所示;
bool lockWasTaken = false;
try
{
Monitor.TryEnter(lockObject, ref lockWasTaken); // returns lockWasTaken = true if it can get a lock
if (!lockWasTaken)
{
log.Warn("Locked by existing request. Request is queued.");
Monitor.Enter(lockObject, ref lockWasTaken); // Goes into the queue to access the object
}
// Do the Singleton processing
}
catch(Exception ex)
{
log.Fatal(ex);
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(lockObject);
}
}
这一切都很好。但我想做的是能够记录有多少排队的请求。 这可能吗?
【问题讨论】:
-
如果你的
if (!lockWasTaken) {块中有一个正在更新的静态变量怎么办。这行得通吗? -
答案是否定的
-
你看过Interlocked类,方法
Increment和Decrement吗?
标签: c# multithreading locking