sshnet / sshnet/SSH.NET

Canceling ConnectAsync lead to crash

Open
#1,530 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
4.4k
Forks
993
Avg merge
9d 21h
Merged PRs (30d)
1

Description

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;
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the supplied ConnectAsync cancellation example and trace how cancellation is handled when the token is canceled immediately. Done means cancellation no longer causes the InvalidOperationException and the connection state remains correct after the task finishes.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
networking
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.