Skip to content

Commit 1da7b6d

Browse files
authored
Add code example for CA2008 rule (#49035) (#49036)
1 parent eae69e4 commit 1da7b6d

File tree

1 file changed

+40
-0
lines changed
  • docs/fundamentals/code-analysis/quality-rules

1 file changed

+40
-0
lines changed

docs/fundamentals/code-analysis/quality-rules/ca2008.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ helpviewer_keywords:
99
- CA2008
1010
author: gewarren
1111
ms.author: gewarren
12+
dev_langs:
13+
- CSharp
1214
---
1315
# CA2008: Do not create tasks without passing a TaskScheduler
1416

@@ -42,6 +44,44 @@ For further information and detailed examples, see [New TaskCreationOptions and
4244

4345
To fix violations, call the method overload that takes a <xref:System.Threading.Tasks.TaskScheduler> and explicitly pass in <xref:System.Threading.Tasks.TaskScheduler.Default%2A> or <xref:System.Threading.Tasks.TaskScheduler.Current%2A> to make the intent clear.
4446

47+
## Example
48+
49+
```csharp
50+
// This code violates the rule.
51+
var badTask = Task.Factory.StartNew(
52+
() =>
53+
{
54+
// ...
55+
}
56+
);
57+
badTask.ContinueWith(
58+
t =>
59+
{
60+
// ...
61+
}
62+
);
63+
64+
// This code satisfies the rule.
65+
var goodTask = Task.Factory.StartNew(
66+
() =>
67+
{
68+
// ...
69+
},
70+
CancellationToken.None,
71+
TaskCreationOptions.None,
72+
TaskScheduler.Default
73+
);
74+
goodTask.ContinueWith(
75+
t =>
76+
{
77+
// ...
78+
},
79+
CancellationToken.None,
80+
TaskContinuationOptions.None,
81+
TaskScheduler.Default
82+
);
83+
```
84+
4585
## When to suppress warnings
4686

4787
This warning is intended primarily for libraries, where the code may be executed in arbitrary environments and where code shouldn't make assumptions about the environment or how the caller of the method may be invoking or waiting on it. It may be appropriate to suppress the warning for projects that represent application code rather than library code.

0 commit comments

Comments
 (0)