using System.Diagnostics;
using System.Threading.Tasks;
private const string _CLRF_ = "\r\n";
private static ManualResetEvent _mre = new ManualResetEvent(true);
private static CancellationTokenSource _cts;
private static ConsoleKey _lastUserChoice;
private static ILogger _logger;
private static ILogger _consoleLogger = new LoggerConfiguration()
.MinimumLevel.Information()
private static ILogger _fileLogger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File("logs.txt")
private static bool _firstRun = true;
private static int _sideServiceLoopCounter = 0;
static async Task Main(string[] args)
ThreadPool.SetMinThreads(1, 1);
ThreadPool.SetMaxThreads(2, 2);
while (_firstRun || UserKeyOn("Repeat this program (y/n) :") is ConsoleKey.Y)
_sideServiceLoopCounter = 0;
static async Task Process()
if (UserKeyOn("Choose your logger by typing (1) for console (2) for file :")
(ConsoleKey.D1 or ConsoleKey.D2 or ConsoleKey.NumPad1 or ConsoleKey.NumPad2))
if (_lastUserChoice is (ConsoleKey.D1 or ConsoleKey.NumPad1))
_logger = _consoleLogger;
_cts = new CancellationTokenSource();
if (UserKeyOn("Start side service as well (y/n) :") is ConsoleKey.Y)
StartSideServiceInThreadPool(_cts.Token);
var sw = new Stopwatch();
var tasks = new Task[100];
for (int i = 0; i < 100; i++)
tasks[i] = Task.Run(() => LoopLog());
await Task.WhenAll(tasks);
Prompt($"Done. It only took {sw.ElapsedMilliseconds} ms");
Prompt($"SideService looped {_sideServiceLoopCounter} times");
for (int i = 0; i < 100; i++)
_logger.Information("Bye bye threadpool. This is ThreadId: " + Thread.CurrentThread.ManagedThreadId);
static void StartSideServiceInThreadPool(CancellationToken token)
ThreadPool.QueueUserWorkItem((state) =>
if (token.IsCancellationRequested)
_logger.Information("This is a sidetask. This is ThreadId: " + Thread.CurrentThread.ManagedThreadId);
Interlocked.Increment(ref _sideServiceLoopCounter);
static ConsoleKey UserKeyOn(string message)
return (_lastUserChoice = Console.ReadKey().Key);
static void Prompt(string message) =>
Console.WriteLine($"{_CLRF_}{message}{_CLRF_}");