SSH.NET icon indicating copy to clipboard operation
SSH.NET copied to clipboard

Canceling ConnectAsync lead to crash

Open MicrovisionCF opened this issue 11 months ago • 0 comments

Hello, I'm trying to establish connection with ConnectAsync and I display a window to allow the user to cancel the attempt. I experiment a System.InvalidOperationException: 'An attempt was made to transition a task to a final state when it had already completed.' each time I cancel.

Here is my simplified code to reproduce with systematic cancelation. Am I missing something ? I'm not familiar with async/await usage so maybe I miss something important...

Thank you in advance.

public bool ConnectAndCancel()
{
	CancellationTokenSource source = new CancellationTokenSource();
	CancellationToken token = source.Token;

	Task task = _sftpClient.ConnectAsync(token);

	source.Cancel();

	try
	{
		task.Wait(token);
	}
	catch (OperationCanceledException)
	{
		Console.WriteLine("Canceled");
	}

	return _sftpClient.IsConnected;
}

MicrovisionCF avatar Nov 08 '24 14:11 MicrovisionCF