Skip to content

Commit

Permalink
Add workaround for AsyncEx synchronization primitives hanging for som…
Browse files Browse the repository at this point in the history
…e time

The minimum number of threads in the .NET thread pool is increased to 4.
This should avoid that an application hangs if a continuation cannot run, because there is no thread to execute it.

Also see: StephenCleary/AsyncEx#107
  • Loading branch information
ravenpride committed Sep 1, 2021
1 parent a55cf25 commit 58cdccd
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace GriffinPlus.Lib.Threading
Expand All @@ -39,6 +40,23 @@ namespace GriffinPlus.Lib.Threading
/// </summary>
public static class TaskCompletionSourceExtensions
{
private const int MinWorkerThreads = 4;

/// <summary>
/// Initializes the <see cref="DefaultAsyncWaitQueue{T}"/> class.
/// </summary>
static TaskCompletionSourceExtensions()
{
// Increase the number of threads in the .NET thread pool on machines with only few CPUs.
// The AsyncEx synchronization primitives in this library need a thread pool thread to execute continuations.
// If there is no thread in the pool the application will hang for some time until the thread pool creates another
// thread to solve the issue. Increasing the number of threads to a higher value than the number of CPUs comes at
// the cost of some performance, so the actual issue should be fixed and this workaround should be eliminated to
// restore the original behavior.
ThreadPool.GetMinThreads(out int minWorkerThreads, out int minCompletionPortThreads);
if (minWorkerThreads < MinWorkerThreads) ThreadPool.SetMinThreads(MinWorkerThreads, minCompletionPortThreads);
}

/// <summary>
/// Attempts to complete a <see cref="TaskCompletionSource{TResult}"/>,
/// propagating the completion of <paramref name="task"/>.
Expand Down

0 comments on commit 58cdccd

Please sign in to comment.