Skip to content

Commit

Permalink
Create Rule “local-copies-to-avoid-race-condition/rule” (#6191)
Browse files Browse the repository at this point in the history
* Create Rule “local-copies-to-avoid-race-condition/rule”

* Update Rule “local-copies-to-avoid-race-condition/rule”

* Merge branch 'SSWConsulting:main' into cms/sylhuang/SSW.Rules.Content/rule/local-copies-to-avoid-race-condition/rule

* Update rules-to-better-code.md

* Update Rule “local-copies-to-avoid-race-condition/rule”

* Update rule.md

---------

Co-authored-by: Tiago Araújo [SSW] <[email protected]>
  • Loading branch information
sylhuang and tiagov8 authored Jul 31, 2023
1 parent 4002bfa commit 6b5f5b4
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions categories/software-development/rules-to-better-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ index:
- installing-3rd-party-libraries
- package-audit-log
- use-package-managers-appropriately
- local-copies-to-resolve-race-condition

---

Expand Down
42 changes: 42 additions & 0 deletions rules/local-copies-to-avoid-race-condition/rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
type: rule
title: Do you use local copies to resolve race condition?
uri: local-copies-to-resolve-race-condition
authors:
- title: Sylvia Huang
url: https://ssw.com.au/people/sylvia-huang
created: 2023-07-31T01:19:28.222Z
guid: f49d4f99-522e-433c-a7ab-0e59d78f03df
---
Code that looks perfectly fine in a single-threaded scenario could be vulnerable to race condition when some value is shared among multiple threads.

<!--endintro-->

Examine the following if-statement:

```csharp
if (A is null || (A.PropertyA == SOME_CONSTANT && B))
{
// some logic
}
```
::: bad
Figure: Bad example - Vulnerable to race condition
:::

When the above code is run single-threaded, the second part of the if-condition would never be reached when A is null. However, if A is shared among multiple threads, the value of A could change from not null to null after passing the first check of if-condition, resulting in a [NRE](https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=net-7.0) in the second check of if-condition.

In order to make the code thread-safe, you should make a local copy of the shared value so that value change caused by another thread would no longer lead to crash.


```csharp
var copyA = A?.PropertyA;

if (A is null || (copyA == SOME_CONSTANT && B))
{
// some logic
}
```
::: good
Figure: Good example - Local copy to resolve race condition
:::

0 comments on commit 6b5f5b4

Please sign in to comment.