43 lines
1.5 KiB
Plaintext
43 lines
1.5 KiB
Plaintext
The instance passed to the https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/synclock-statement[`SyncLock` statement] should be a dedicated private field.
|
|
|
|
include::../why-dotnet.adoc[]
|
|
|
|
The following objects are considered potentially prone to accidental lock sharing:
|
|
|
|
* a reference to https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/program-structure/me-my-mybase-and-myclass#me[Me]: if the instance is publicly accessible, the lock might be shared
|
|
* a https://learn.microsoft.com/en-us/dotnet/api/system.type[Type] object: if the type class is publicly accessible, the lock might be shared
|
|
* a https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/string-data-type[String] literal or instance: if any other part of the program uses the same string, the lock is shared because of interning
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,vbnet,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
Public Sub MyLockingMethod()
|
|
SyncLock Me 'Noncompliant
|
|
' ...
|
|
End SyncLock
|
|
End Sub
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,vbnet,diff-id=1,diff-type=compliant]
|
|
----
|
|
Private lockObj As New Object()
|
|
Public Sub MyLockingMethod()
|
|
SyncLock lockObj
|
|
' ...
|
|
End SyncLock
|
|
End Sub
|
|
----
|
|
|
|
include::../resources-dotnet.adoc[]
|
|
|
|
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/synclock-statement[SyncLock Statement]
|
|
|
|
include::../rspecator.adoc[]
|