Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 61ad2cb

Browse files
authored
Add regression test for Task handling of suppressed ExecutionContext flow (#28809)
1 parent 368511a commit 61ad2cb

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
<Compile Include="MethodCoverage.cs" />
1818
<Compile Include="CESchedulerPairTests.cs" />
1919
<!-- Task -->
20+
<Compile Include="Task\ExecutionContextFlowTest.cs" />
2021
<Compile Include="Task\RunContinuationsAsynchronouslyTests.cs" />
2122
<Compile Include="Task\TPLTestException.cs" />
2223
<Compile Include="Task\TaskRunSyncTests.cs" />
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.Collections.Generic;
6+
using System.Reflection;
7+
using System.Runtime.CompilerServices;
8+
using Xunit;
9+
10+
namespace System.Threading.Tasks.Tests
11+
{
12+
public class ExecutionContextFlowTest
13+
{
14+
[Theory]
15+
[InlineData(false)]
16+
[InlineData(true)]
17+
public void SuppressFlow_TaskCapturesContextAccordingly(bool suppressFlow)
18+
{
19+
Assert.False(ExecutionContext.IsFlowSuppressed());
20+
if (suppressFlow) ExecutionContext.SuppressFlow();
21+
try
22+
{
23+
var asyncLocal = new AsyncLocal<int>();
24+
Task.Factory.StartNew(() => asyncLocal.Value = 42, CancellationToken.None, TaskCreationOptions.None, new InlineTaskScheduler()).Wait();
25+
Assert.Equal(suppressFlow ? 42 : 0, asyncLocal.Value);
26+
}
27+
finally
28+
{
29+
if (suppressFlow) ExecutionContext.RestoreFlow();
30+
}
31+
}
32+
33+
private sealed class InlineTaskScheduler : TaskScheduler
34+
{
35+
protected override void QueueTask(Task task) => TryExecuteTask(task);
36+
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
37+
protected override IEnumerable<Task> GetScheduledTasks() => null;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)