From 30d79c7b316ae5cc7ba590bf6537e684e4a8216b Mon Sep 17 00:00:00 2001 From: Igor Milavec Date: Sun, 28 Nov 2021 15:42:04 +0100 Subject: [PATCH] Start MessageListener with ThreadAbstraction.ExecuteThreadLongRunning (#902) * Fix Thread pool exhaustion due to MessageListener running on ThreadPool * Mark long running thread as background --- src/Renci.SshNet/Abstractions/ThreadAbstraction.cs | 9 +++++++-- src/Renci.SshNet/Session.cs | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs index ee21ec7ef..8c344404b 100644 --- a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs +++ b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs @@ -21,12 +21,17 @@ public static void Sleep(int millisecondsTimeout) public static void ExecuteThreadLongRunning(Action action) { + if (action == null) + throw new ArgumentNullException("action"); + #if FEATURE_THREAD_TAP var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning; System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions); #else - var thread = new System.Threading.Thread(() => action()); - thread.Start(); + new System.Threading.Thread(() => action()) + { + IsBackground = true + }.Start(); #endif } diff --git a/src/Renci.SshNet/Session.cs b/src/Renci.SshNet/Session.cs index 0748b8dac..d2bf4bdf1 100644 --- a/src/Renci.SshNet/Session.cs +++ b/src/Renci.SshNet/Session.cs @@ -618,7 +618,8 @@ public void Connect() _messageListenerCompleted.Reset(); // Start incoming request listener - ThreadAbstraction.ExecuteThread(() => MessageListener()); + // ToDo: Make message pump async, to not consume a thread for every session + ThreadAbstraction.ExecuteThreadLongRunning(() => MessageListener()); // Wait for key exchange to be completed WaitOnHandle(_keyExchangeCompletedWaitHandle);