/
S2445_c#.html
44 lines (41 loc) · 1.42 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
<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>The story is very similar for locking on a local variable or on a new instance; two different threads running the method in parallel would lock on
two different object instances, completely undermining the synchronization.</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>