-
-
Save Sheepings/fde1c03b68b6abd1f0ff704fccee84a4 to your computer and use it in GitHub Desktop.
Execution Context not capturing thread id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Collections.Generic; | |
public class Test | |
{ | |
static ExecutionContext _ec; | |
static int _mainThreadId; | |
static ConsoleColor _mainConsoleColor; | |
static object _consoleLock; | |
static void Main() | |
{ | |
_mainThreadId = Thread.CurrentThread.ManagedThreadId; | |
_mainConsoleColor = Console.ForegroundColor; | |
_consoleLock = new object(); | |
Console.WriteLine($"ThreadId: {_mainThreadId}"); | |
_ec = ExecutionContext.Capture(); | |
var tasks = new List<Task>(); | |
for(int i = 0; i < 20; i++) | |
{ | |
tasks.Add(Task.Run(() => | |
{ | |
Console.WriteLine($"Task ThreadId: {Thread.CurrentThread.ManagedThreadId}"); | |
ExecutionContext.Run(_ec.CreateCopy(), delegate | |
{ | |
lock (_consoleLock) | |
{ | |
int id = Thread.CurrentThread.ManagedThreadId; | |
Console.ForegroundColor = id == _mainThreadId ? ConsoleColor.Green : ConsoleColor.Red; | |
Console.WriteLine($"EC ThreadId: {Thread.CurrentThread.ManagedThreadId}"); | |
Console.ForegroundColor = _mainConsoleColor; | |
} | |
}, null); | |
})); | |
} | |
Task.WaitAll(tasks.ToArray()); | |
Console.WriteLine("Done. Press any key to exit."); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment