Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/core/testing/mstest-analyzers/mstest0045.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ A test method uses <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAtt

## Rule description

There's no way to gracefully abort a running thread. There are two ways for a timeout to work:

- 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*.
- Request cancellation once the timeout is reached, and it's the test responsibility to terminate on request. This is *cooperative cancellation*.

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.

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.
Expand All @@ -38,6 +43,21 @@ When using cooperative cancellation mode, MSTest only triggers cancellation of t

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.

```csharp
[TestClass]
public class TestClass1
{
public TestContext TestContext { get; set; }

[Timeout(TimeoutValue, CooperativeCancellation = true)]
[TestMethod]
public void TestMethod1()
{
// Respect TestContext.CancellationTokenSource.Token
}
}
```

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.

## When to suppress warnings
Expand Down