Last active
February 9, 2022 12:13
-
-
Save cdaven/80494dcf9a4a03b698ef9680f8cae00f to your computer and use it in GitHub Desktop.
Example of synchronous blocking causing deadlock
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
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