Skip to content

Commit bc2fb85

Browse files
authored
Update mstest0045.md
1 parent f3f7659 commit bc2fb85

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

docs/core/testing/mstest-analyzers/mstest0045.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ A test method uses <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAtt
3030

3131
## Rule description
3232

33+
There is no way to gracefully abort a running thread. So, for a timeout to work, there are two ways:
34+
35+
1. Stop observing the thread running the test. But this can be problematic in many cases and might make the remaining tests unstable due to potential race conditions. This is non-cooperative cancellation.
36+
2. A cancellation is requested once the timeout is reached, and it's the test responsibility to terminate on request. This is cooperative cancellation.
37+
3338
When using <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAttribute>, you should set `CooperativeCancellation` to `true` to enable cooperative cancellation. Without cooperative cancellation, the test framework stops observing the test execution when the timeout is reached, but the test continues running in the background. This can lead to problems for other tests or cleanup steps, as the original test is still executing and might interfere with subsequent operations.
3439

3540
When using cooperative cancellation mode, MSTest only triggers cancellation of the token and you're responsible for flowing and utilizing the test context token in your test code. This mode aligns with the default behavior of cancellation in .NET.
@@ -38,6 +43,10 @@ When using cooperative cancellation mode, MSTest only triggers cancellation of t
3843

3944
Use the provided code fixer to automatically set the `CooperativeCancellation` property to `true` on the <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAttribute>. You can also manually add the property if needed.
4045

46+
```csharp
47+
[Timeout(TimeoutValue, CooperativeCancellation = true)]
48+
```
49+
4150
Alternatively, you can configure cooperative cancellation globally in your [runsettings](/dotnet/core/testing/unit-testing-mstest-configure#mstest-element) or [testconfig.json](/dotnet/core/testing/unit-testing-mstest-configure#timeout-settings) file to apply this setting to all timeout attributes in your test project.
4251

4352
## When to suppress warnings

0 commit comments

Comments
 (0)