我怎樣才能將這段代碼:只允許一個線程訪問C#中的資源的簡單方法?
try
{
lock (lockForSomethingInUse)
{
somethingInUse = true;
// use it
}
}
finally
{
somethingInUse = false;
}
有了:
using (lockForSomething)
{
// use it
}
我怎樣才能將這段代碼:只允許一個線程訪問C#中的資源的簡單方法?
try
{
lock (lockForSomethingInUse)
{
somethingInUse = true;
// use it
}
}
finally
{
somethingInUse = false;
}
有了:
using (lockForSomething)
{
// use it
}
如果你想使用lock
,並能要知道當前是否僅使用一個語句/變量來獲取鎖,則可以嘗試使用以下類。他們不會因爲可讀性而獲得任何獎勵,但他們允許您使用using
進行鎖定,只要您想要。
class DisposableLock
{
public bool IsAcquired { get; set; }
class Handle : IDisposable
{
private DisposableLock parent;
public void Dispose()
{
parent.IsAcquired = false;
Monitor.Exit(parent);
}
}
public IDisposable Acquire()
{
var handle = new Handle();
handle.parent = this;
handle.parent.IsAcquired = true;
Monitor.Enter(this);
return handle;
}
}
用法:
DisposableLock lockForSomething = new DisposableLock();
// ...
using (lockForSomething.Acquire())
{
// do something
}
然後可以使用lockForSomething.IsAcquired
在其他一些地方,檢查是否正在使用的資源。內部類實施IDisposable
是爲了確保您不會意外地使用using (lockForSomething)
。
lock()
已經產生嘗試/終於在引擎蓋下阻擋所以就刪除它,一切都會好起來
看起來像問題被改變,因爲最初沒有提到'與使用(lockForSomething)'但'與鎖(lockForSomething)'' – sll
此代碼:
using (lockForSomething)
{
// use it
}
暗示臨時當使用的代碼塊退出時,lockForSomething被處置。除非lockForSomething屬於更廣的範圍(不,不!),否則不同的線程無法訪問它。
即使發生異常,不會失敗,因爲:
lock (x) ...
是一樣的:
System.Threading.Monitor.Enter(x);
try {
...
}
finally {
System.Threading.Monitor.Exit(x);
}
爲什麼不使用鎖定語句? 'lock(lockForSomethingInUse){...}' – Peter
當你想使用鎖時,有什麼問題? – sll