/
S2445_c#.html
48 lines (45 loc) · 1.76 KB
/
S2445_c#.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<p>Locking on a class field synchronizes not on the field itself, but on the object assigned to it. So locking on a non-<code>readonly</code> field
makes it possible for the field’s value to change while a thread is in a block locked on the old value. That would allow a second thread, locked on
the new value, to enter the block at the same time.</p>
<p>Locking on a <code>readonly</code> field of a class which is not <code>private</code> allows external code to lock the field, potentially
interfering with synchronization by methods of that class.</p>
<p>Locking on a local variable or on a new instance undermines the synchronization: two different threads running the method in parallel would lock on
two different object instances.</p>
<p>Locking on a string literal is even more dangerous: depending on whether the string is interned or not, different threads may or may not
synchronize on the same object instance.</p>
<h2>Noncompliant Code Example</h2>
<pre>
private string color = "red";
private void DoSomething()
{
lock (color) // Noncompliant; lock is actually on object instance "red" referred to by the color variable
{
//...
color = "green"; // other threads now allowed into this block
// ...
}
lock (new object()) // Noncompliant this is a no-op.
{
// ...
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
private string color = "red";
private readonly object lockObj = new object();
private void DoSomething()
{
lock (lockObj)
{
//...
color = "green";
// ...
}
}
</pre>
<h2>See</h2>
<ul>
<li> <a href="https://cwe.mitre.org/data/definitions/412">MITRE, CWE-412</a> - Unrestricted Externally Accessible Lock </li>
<li> <a href="https://cwe.mitre.org/data/definitions/413">MITRE, CWE-413</a> - Improper Resource Locking </li>
</ul>