Skip to content

Instantly share code, notes, and snippets.

@cdaven
Last active February 9, 2022 12:13
Show Gist options
  • Save cdaven/80494dcf9a4a03b698ef9680f8cae00f to your computer and use it in GitHub Desktop.
Save cdaven/80494dcf9a4a03b698ef9680f8cae00f to your computer and use it in GitHub Desktop.
Example of synchronous blocking causing deadlock
async Task PauseAsync()
{
// Normal asynchronous method call
await Task.Delay(1000);
}
void Pause()
{
// Synchronous method blocking on asynchronous method
PauseAsync().Wait();
}
var maxNumWorkerThreads = Environment.ProcessorCount;
Console.WriteLine($"Limit number of worker threads to {maxNumWorkerThreads}");
ThreadPool.SetMaxThreads(maxNumWorkerThreads, maxNumWorkerThreads);
// When number of tasks equals maxNumWorkerThreads - 1, it will deadlock
var numTasks = maxNumWorkerThreads - 1;
var tasks = new List<Task>();
for (var i = 0; i < numTasks; i++)
{
Console.WriteLine($"Starting task in worker thread #{i + 1}");
tasks.Add(Task.Run(() => Pause()));
}
Console.WriteLine("Waiting for tasks to complete");
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All tasks complete");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment