'C# SSH command execute

i need a small help with my app. When I press the button the app freezes until ssh complete the commnand which was sent. I tried solution from C# application freezes but when I tried to use Task.Factory.StartNew(()... i dont have a output in console. There is my code:

var cmd = SSH.CreateCommand("apt update && apt upgrade -y");
                    var asynch = cmd.BeginExecute();
                    var reader = new StreamReader(cmd.OutputStream);

                    while (!asynch.IsCompleted)
                    {
                        var result = reader.ReadToEnd();
                        if (string.IsNullOrEmpty(result))
                            continue;
                        Console.Write(result);
                    }
                    cmd.EndExecute(asynch); 

Does anyone have anything to do with it?



Solution 1:[1]

You are probably blocking your GUI thread with your while loop.

You need to run your code async.

public static void Main(String[] args)
{
    Task sshTask = RunCommand();
}


public static async Task RunCommand()
{
    var cmd = SSH.CreateCommand("apt update && apt upgrade -y");
    var asynch = cmd.BeginExecute();
    var reader = new StreamReader(cmd.OutputStream);

    while (!asynch.IsCompleted)
    {
        var result = reader.ReadToEnd();
        if (string.IsNullOrEmpty(result))
            continue;
        Console.Write(result);
    }
    cmd.EndExecute(asynch);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VarChar42