Skip to content

WriteAsync doesn't complete with ReadAsync running in background #1707

@DeepakParamkusam

Description

@DeepakParamkusam

I have a simple program below that call ReadAsync in a concurrent task. On running the program, the connection succeeds and I see the initial preamble. But the program hangs on hitting WriteAsync, the await never completes. Am I doing something wrong? Or am I not supposed to use these async methods?

Same behavior on .NET 9 and .Net framework 4.8.1 with v2025.0.0

class Program
{
    private async static Task Main(string[] args)
    {
        using var cts = new CancellationTokenSource();
        using var client = new SshClient(args[0], 22, args[1], args[2]);
        await client.ConnectAsync(cts.Token);
        await using var stream = client.CreateShellStream("test", 80, 24, 80, 24, 1024);
        var task = Task.Run(() => ReadStream(stream, cts.Token));
        var command = Encoding.ASCII.GetBytes("ls\n");

        // Continue after key press
        Console.ReadKey(true)

        await stream.WriteAsync(command, cts.Token);
        await stream.FlushAsync(cts.Token);

        // Continue after key press
        Console.ReadKey(true)

        cts.Cancel();
        await task;
    }

    private static async Task ReadStream(ShellStream stream, CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            try
            {
                var buffer = new byte[1024];
                var readLength = await stream.ReadAsync(buffer, token);
                Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, readLength));
            }
            catch (OperationCanceledException) { }
        }
    }
}

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