如何执行可以显示结果的异步/等待命令



我尝试了以下代码在Task.Run中执行命令。

SshClient ssh;
public Form1()
{
InitializeComponent();
//BackGround Login is needed.
ConnectionInfo info = new ConnectionInfo(hostNameOrIpAddr, portNo, userName,
new AuthenticationMethod[] {
new PasswordAuthenticationMethod(userName, passWord)
ssh = new SshClient(info);
ssh.Connect();
cmd = ssh.CreateCommand(commandString);
}
private void button1_Click(object sender, EventArgs e)
{
Task.Run(()=>{
SshCommand cmd = ssh.CreateCommand(commandString);
cmd.Execute();
Console.WriteLine(cmd.Result.ToString());
;});
}

但它效果不佳。 原因可能是在启动任务后立即释放流。

使用 async/await 的方法之一如下:

注意:async 关键字将方法转换为异步方法,这允许您在其正文中使用 await 关键字。

private async void button1_Click(object sender, EventArgs e) {
var result = await Task.Run(() => RunSshCmd());
Console.WriteLine(result);
}

假设运行 ssh 命令需要 5 秒才能完成,这只是一个例子。

private string RunSshCmd() {       
Thread.Sleep(5000);
return "Done.";
}

注意:await 只能在异步方法中使用。

最新更新