Skip to content

Commit fe6d490

Browse files
Update mstest0045.md (#47612)
* Update mstest0045.md * Update mstest0045.md * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> --------- Co-authored-by: Genevieve Warren <[email protected]>
1 parent c8853c9 commit fe6d490

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

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

Lines changed: 20 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's no way to gracefully abort a running thread. There are two ways for a timeout to work:
34+
35+
- 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+
- Request cancellation 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,21 @@ 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+
[TestClass]
48+
public class TestClass1
49+
{
50+
public TestContext TestContext { get; set; }
51+
52+
[Timeout(TimeoutValue, CooperativeCancellation = true)]
53+
[TestMethod]
54+
public void TestMethod1()
55+
{
56+
// Respect TestContext.CancellationTokenSource.Token
57+
}
58+
}
59+
```
60+
4161
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.
4262

4363
## When to suppress warnings

0 commit comments

Comments
 (0)