-
-
Save benaadams/08e5af7881f25c6dd2577a92de182a73 to your computer and use it in GitHub Desktop.
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.Diagnostics; | |
using System.Threading; | |
using System.Threading.Tasks; | |
class Program | |
{ | |
private static DateTime s_start; | |
private static int s_completedWaits; | |
private static WaitCallback s_async = OutputAsync; | |
private static WaitCallback s_blocking = OutputBlocking; | |
static void Main() | |
{ | |
s_start = DateTime.UtcNow; | |
// Blocking in ThreadPool | |
ThreadPool.QueueUserWorkItem(s_blocking, new Params { Sequence = 1, Ticks = Environment.TickCount }); | |
// Async in ThreadPool | |
//ThreadPool.QueueUserWorkItem(s_async, new Params { Sequence = 1, Ticks = Environment.TickCount }); | |
// Don't let main thread exit | |
Task.Delay(-1).Wait(); | |
} | |
static void OutputAsync(object obj) | |
{ | |
OutputAndSchedule((Params)obj, s_async); | |
_ = Async(); | |
static async Task Async() | |
{ | |
await WaitAsync(); | |
Interlocked.Increment(ref s_completedWaits); | |
} | |
} | |
static void OutputBlocking(object obj) | |
{ | |
OutputAndSchedule((Params)obj, s_blocking); | |
WaitAsync().Wait(); | |
Interlocked.Increment(ref s_completedWaits); | |
} | |
private static void OutputAndSchedule(Params value, WaitCallback callback) | |
{ | |
var ticks = Environment.TickCount; | |
var threadCount = Process.GetCurrentProcess().Threads.Count; | |
Console.WriteLine($"Seq {value.Sequence} => WaitsCompleted {s_completedWaits}, Elapsed: {(DateTime.UtcNow - s_start).TotalSeconds:0.0}sec, Delay: {(ticks - value.Ticks) / 1000.0}secs, ThreadCount: {threadCount}"); | |
ThreadPool.QueueUserWorkItem(callback, new Params { Sequence = value.Sequence + 1, Ticks = Environment.TickCount }); | |
} | |
static async Task WaitAsync() | |
{ | |
await Task.Delay(10000); | |
} | |
struct Params | |
{ | |
public int Sequence; | |
public int Ticks; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment