CA2002:請勿鎖定具有弱式識別的物件
型別名稱 |
DoNotLockOnObjectsWithWeakIdentity |
CheckId |
CA2002 |
分類 |
Microsoft.Reliability |
中斷變更 |
中斷 |
原因
執行緒嘗試取得具有弱式識別 (Identity) 之物件的鎖定。
規則描述
可以跨應用程式定義域範圍直接存取的物件,即所謂具有弱式識別的物件。嘗試取得具有弱式識別之物件鎖定的執行緒,可以被不同應用程式定義域中具有相同物件鎖定的第二個執行緒所封鎖。下列型別具有弱式識別,而且規則會將它們加上旗標:
如何修正違規
若要修正此規則的違規情形,請使用未列於<描述>一節之型別中的物件。
隱藏警告的時機
請勿隱藏此規則的警告。
相關規則
範例
下列範例會顯示一些違反規則的物件鎖定。
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Threading
Namespace ReliabilityLibrary
Class WeakIdentities
Sub SyncLockOnWeakId1()
SyncLock GetType(WeakIdentities)
End SyncLock
End Sub
Sub SyncLockOnWeakId2()
Dim stream As New MemoryStream()
SyncLock stream
End SyncLock
End Sub
Sub SyncLockOnWeakId3()
SyncLock "string"
End SyncLock
End Sub
Sub SyncLockOnWeakId4()
Dim member As MemberInfo = _
Me.GetType().GetMember("SyncLockOnWeakId1")(0)
SyncLock member
End SyncLock
End Sub
Sub SyncLockOnWeakId5()
Dim outOfMemory As New OutOfMemoryException()
SyncLock outOfMemory
End SyncLock
End Sub
End Class
End Namespace
using System;
using System.IO;
using System.Reflection;
using System.Threading;
namespace ReliabilityLibrary
{
class WeakIdentities
{
void LockOnWeakId1()
{
lock(typeof(WeakIdentities)) {}
}
void LockOnWeakId2()
{
MemoryStream stream = new MemoryStream();
lock(stream) {}
}
void LockOnWeakId3()
{
lock("string") {}
}
void LockOnWeakId4()
{
MemberInfo member = this.GetType().GetMember("LockOnWeakId1")[0];
lock(member) {}
}
void LockOnWeakId5()
{
OutOfMemoryException outOfMemory = new OutOfMemoryException();
lock(outOfMemory) {}
}
}
}