You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We run into the same issue, but on Linux. Can confirm that it's waiting on _messageListenerCompleted.WaitOne() inside Disconnect.
We have a wrapper class around the SshClient and we worked around the issue by disconnecting the socket through reflection if necessary after a 2 second delay and setting the waithandle. The dispose method of our wrapper class:
publicvoidDispose(){if(_client==null)return;Task.Run(()=>{_log.Debug("Disposing _client");vartimer=newSystem.Timers.Timer();timer.Interval=2000;timer.AutoReset=false;timer.Elapsed+=(s,e)=>{try{varsessionField=_client.GetType().GetProperty("Session",BindingFlags.NonPublic|BindingFlags.Instance);if(sessionField!=null){varsession=sessionField.GetValue(_client);if(session!=null){varsocketField=session.GetType().GetField("_socket",BindingFlags.NonPublic|BindingFlags.Instance);if(socketField!=null){varsocket=(Socket)socketField.GetValue(session);if(socket!=null){_log.Debug($"Socket state: Connected = {socket.Connected}, Blocking = {socket.Blocking}, Available = {socket.Available}, LocalEndPoint = {socket.LocalEndPoint}, RemoteEndPoint = {socket.RemoteEndPoint}");_log.Debug("Set _socket to null");try{socket.Dispose();}catch(Exceptionex){_log.Debug("Exception disposing _socket",ex);}socketField.SetValue(session,null);}else{_log.Debug("_socket was null");}}varmessageListenerCompletedField=session.GetType().GetField("_messageListenerCompleted",BindingFlags.NonPublic|BindingFlags.Instance);varmessageListenerCompleted=(EventWaitHandle)messageListenerCompletedField.GetValue(session);if(messageListenerCompleted!=null){varwaitHandleSet=messageListenerCompleted.WaitOne(0);_log.Debug($"_messageListenerCompleted was set = {waitHandleSet}");if(!waitHandleSet){_log.Debug($"Calling Set()");messageListenerCompleted.Set();}}else{_log.Debug("_messageListenerCompleted was null");}}else{_log.Debug("Session was null");}}}catch(Exceptionex){_log.Debug($"Exception in Timer event handler",ex);}};timer.Start();_client.Dispose();_log.Info("Disposed _client");});}
A typical log when it fails to disconnect:
But it usually disconnects just fine, not disconnecting is the exception. The ratios are 20 failures for 700 successful disconnects in about 12 hours.
Reacted by Illia, Brent Williams, AraHaan and Panagis Artoumas
I should add that it happens much more often that _socket is already null when disconnecting hangs, and only _messageListenerCompleted.Set() wasn't called yet. So the log usually says this when the disconnect fails:
So the _socket still being connected is the exception.
I have the same issue using .NET Core 2.0 on macOS Sierra 10.12.6 (16G1212)
using (var client = new SshClient(host, username, password))
{
client.Connect();
var command = client.CreateCommand("df -H");
var result = command.Execute();
Console.WriteLine(result);
client.Disconnect();
}
Ran into the same problem on macOS High Sierra, 10.13.5, dotnet core version 2.1.300
It fails to disconnect and also hangs at the end of "using (var client = new SftpClient(...))"
@drieseng We use the latest (2016.1.0). From our logs, in about 4% of cases it hasn't set the waithandle (see our workaround code above) so it would wait indefinitely. Ever since upgrading to .NET Core 2.1 we haven't seen the cases where the socket was still connected, so I think that's solved by that upgrade, but it was really rare before so it might be a coincidence. I think the occurrence of the issue is more or less random and probably a timing thing.
@drieseng - Getting it on macOS High Sierra dotnet core v2.1.301. Using the latest nuget package 2016.1.0. Easily reproducible... just open a connection and try to call Disconnect.
Is this issue fixed with 2020.0.1 and .NET 5.0 or shall I simply avoid calling Disconnect() method and just Dispose() the connection?
Asking because I don't see that Shutdown(SocketShutdown.Both) was finally implemented into any latest SSH.NET release.
Thanks
@effolkronium thanks for the tip, but my code needs to support Win Server 2012 and 2016 too where no windows native ssh exists (I would need to install PuTTY Plink or similar 3rd party)
It hangs in Disconnect calling from Dispose at _ = _messageListenerCompleted.WaitOne();
public void Disconnect()
{
DiagnosticAbstraction.Log(string.Format("[{0}] Disconnecting session.", ToHex(SessionId)));
// send SSH_MSG_DISCONNECT message, clear socket read buffer and dispose it
Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
// at this point, we are sure that the listener thread will stop as we've
// disconnected the socket, so lets wait until the message listener thread
// has completed
if (_messageListenerCompleted != null)
{
_ = _messageListenerCompleted.WaitOne();
}
}
I fixed it by adding _ = _messageListenerCompleted.WaitOne(1000);
and _ = _messageListenerCompleted?.Set(); in MessageListener.
Activity
keyant commentedon Dec 18, 2017
I also encountered the same problem ( on OSX High Sierra, too).
I found the code is locked by this line:
_messageListenerCompleted.WaitOne();in the methodDisconnect()ofSession.cs.oktinaut commentedon Jan 3, 2018
The problem occurs on Sierra as well (using .NET Core 2.0).
HalfLegend commentedon Jan 11, 2018
Same issue, also OSX High Sierra
Not only sshClient, scpClient also have the issue.
Any update?
HalfLegend commentedon Jan 11, 2018
Now I am using the following code to avoid the issue:
and kill these threads later.
Though the threads are blocked, the socket resources are in fact freed successfully before _messageListenerCompleted.WaitOne() is called.
JulianRooze commentedon Jan 18, 2018
We run into the same issue, but on Linux. Can confirm that it's waiting on
_messageListenerCompleted.WaitOne()insideDisconnect.We have a wrapper class around the
SshClientand we worked around the issue by disconnecting the socket through reflection if necessary after a 2 second delay and setting the waithandle. The dispose method of our wrapper class:A typical log when it fails to disconnect:
But it usually disconnects just fine, not disconnecting is the exception. The ratios are 20 failures for 700 successful disconnects in about 12 hours.
JulianRooze commentedon Jan 19, 2018
I should add that it happens much more often that
_socketis already null when disconnecting hangs, and only_messageListenerCompleted.Set()wasn't called yet. So the log usually says this when the disconnect fails:So the
_socketstill being connected is the exception.bloudraak commentedon Jan 27, 2018
I have the same issue using .NET Core 2.0 on macOS Sierra 10.12.6 (16G1212)
neseih commentedon Jun 5, 2018
Just ran into the same issue on Ubuntu 16.04, dotnet core 2.1
jolosimeon commentedon Jun 25, 2018
Ran into the same problem on macOS High Sierra, 10.13.5, dotnet core version 2.1.300
It fails to disconnect and also hangs at the end of "using (var client = new SftpClient(...))"
drieseng commentedon Jun 26, 2018
What version of SSH.NET are you using?
Can you easily reproduce this issue, or does it only happen on some occasion?
JulianRooze commentedon Jun 27, 2018
@drieseng We use the latest (
2016.1.0). From our logs, in about 4% of cases it hasn't set the waithandle (see our workaround code above) so it would wait indefinitely. Ever since upgrading to .NET Core 2.1 we haven't seen the cases where the socket was still connected, so I think that's solved by that upgrade, but it was really rare before so it might be a coincidence. I think the occurrence of the issue is more or less random and probably a timing thing.HalfLegend commentedon Jul 16, 2018
@drieseng Any update?
It could be easily reproduced on mac os. Just open a ssh client and close it
cravall commentedon Jul 19, 2018
@drieseng - Getting it on macOS High Sierra dotnet core v2.1.301. Using the latest nuget package
2016.1.0. Easily reproducible... just open a connection and try to callDisconnect.drieseng commentedon Jul 19, 2018
I don't have a mac :(
Can you reproduce it on Linux?
cravall commentedon Jul 19, 2018
Just tried to reproduce it in docker and couldn't... which I guess is a good thing because that's what we're using outside of our dev environments.
Still, would be good to have it fixed for dev purposes. I'll see if I can have a crack at fixing but honestly, I wouldn't know where to start 😄
108 remaining items
aberbegall commentedon Jun 13, 2022
Is this issue fixed with 2020.0.1 and .NET 5.0 or shall I simply avoid calling Disconnect() method and just Dispose() the connection?
Asking because I don't see that
Shutdown(SocketShutdown.Both)was finally implemented into any latest SSH.NET release.Thanks
ilqvya commentedon Jun 13, 2022
Better use the Process.Start to call the native to windows "ssh" program and pass args to it. The project is a mess of multithreading issues
aberbegall commentedon Jun 13, 2022
@effolkronium thanks for the tip, but my code needs to support Win Server 2012 and 2016 too where no windows native ssh exists (I would need to install PuTTY Plink or similar 3rd party)
oguzhantopcu commentedon Jun 13, 2022
aberbegall commentedon Jun 13, 2022
@oguzhantopcu Is this the update your fork contains or is there anything else to consider?
Thanks
oguzhantopcu commentedon Jun 13, 2022
Yeah, that one line code fixes that hang problem. My app makes thousands of sftp connections everyday without any problem.
erik-wramner commentedon Jul 1, 2022
Then perhaps we could get that line into the official version?
oguzhantopcu commentedon Dec 30, 2023
is there anyone that still faces this issue? i want to ditch my custom code and use the original one. maybe it is fixed in .net core side.
@drieseng btw why we are not using
SocketShutdown.Bothinstead ofSocketShutdown.Send?as like here OctopusDeploy@7e8bf58
Kalyxt commentedon Feb 1, 2024
Yes its still issue for me, If I connect to remote client, and I lost connection, it hangs on
Disconnect.oguzhantopcu commentedon Feb 1, 2024
.net core version?
Kalyxt commentedon Feb 1, 2024
I am trying in on .NET Framework 4.7.2 project.
I can easily test it in this order:
Disconnectcalling fromDisposeat_ = _messageListenerCompleted.WaitOne();I fixed it by adding
_ = _messageListenerCompleted.WaitOne(1000);and
_ = _messageListenerCompleted?.Set();in MessageListener.VanIseghemThomas commentedon Sep 25, 2025
Stil an issue for me when used in the Unity engine on 2025.0.0. Narrowed it down to the
SshClient.Disconnect&SshClient.Disposecall.ilqvya commentedon Sep 25, 2025
Just use built in ssh cmd tool instead. The project is very buggy
Remove calls to Socket.Poll and use SocketShutdown.Both
Remove calls to Socket.Poll and use SocketShutdown.Both (#1706)