Skip to content

Instantly share code, notes, and snippets.

@szehetner
Created November 15, 2023 11:10
Show Gist options
  • Save szehetner/47515ee0f28e2ca9d4990d60ac230a07 to your computer and use it in GitHub Desktop.
Save szehetner/47515ee0f28e2ca9d4990d60ac230a07 to your computer and use it in GitHub Desktop.
Thread Suspension Repro
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ThreadSuspension
{
internal class Program
{
private static readonly CancellationTokenSource _cts = new CancellationTokenSource();
private static IIdleStrategy _idleStrategy = new NoOpIdleStrategy();
static void Main(string[] args)
{
var thread = new Thread(WorkLoop);
thread.Start();
var watch = new Stopwatch();
for (int i = 0; i < 50; i++)
{
watch.Restart();
GC.Collect();
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
_cts.Cancel();
thread.Join();
}
public static void WorkLoop(object? _)
{
while (!_cts.IsCancellationRequested)
{
_idleStrategy.Idle(0);
}
}
}
public interface IIdleStrategy
{
void Idle(int workCount);
}
public class NoOpIdleStrategy : IIdleStrategy
{
[MethodImpl(MethodImplOptions.NoInlining)]
public void Idle(int workCount)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment