Skip to content

Cancellation of FtpConnection.ReadFromStreamAsync causes UnobservedTaskException #131

Open
@cjzzz

Description

@cjzzz

In FtpConnection.ReadFromStreamAsync, readTask is started using the cancellation token passed into the method, but tcs is also created which has its result set when the cancellation token is cancelled:

protected override async Task<int> ReadFromStreamAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
	var readTask = Stream
	   .ReadAsync(buffer, offset, length, cancellationToken);

	var tcs = new TaskCompletionSource<object?>();
	using var registration = cancellationToken.Register(() => tcs.TrySetResult(null));
	var resultTask = await Task.WhenAny(readTask, tcs.Task)
	   .ConfigureAwait(false);

	if (cancellationToken.IsCancellationRequested)
	{
		Logger?.LogTrace("Cancelled through CancellationToken");
		return 0;
	}
...

This can cause resultTask to complete when tcs.Task is complete, and the exception from the cancellation of readTask is never observed. causing an UnobservedTaskException.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions