我正在使用 ASP.NET Core Web API 構建一個 Web 應用程式。它用于與 Linux 服務器的 SSH 通信,所以我必須等待服務器回應。現在我正在使用Thread.Sleep(2000);就像下面的代碼一樣。
但我確信有更好的方法來做到這一點;也許Task.Wait?在這樣的 Web API 場景中我應該選擇哪一個?
非常感謝
using System;
using Renci.SshNet;
using System.Threading;
namespace SSHTest
{
class Program
{
static void Main(string[] args)
{
//Connection information
string user = "xx";
string pass = "xx";
string host = "uxx.ac.uk";
using (var client = new SshClient(host, user, pass))
{
client.Connect();
var cmd = client.CreateCommand("echo 123");
var asynch = cmd.BeginExecute();
while (!asynch.IsCompleted)
{
// Waiting for command to complete...
Thread.Sleep(2000);
}
var result = cmd.EndExecute(asynch);
Console.WriteLine(result);
client.Disconnect();
}
}
}
}
uj5u.com熱心網友回復:
您可以使用asynch.AsyncWaitHandle.WaitOne();而不是顯式while回圈來實作相同的行為。
或者,您可以Task使用Task.Factory.FromAsync.
您的代碼將如下所示:
using System;
using Renci.SshNet;
using System.Threading;
namespace SSHTest
{
class Program
{
static async Task Main(string[] args)
{
//Connection information
string user = "xx";
string pass = "xx";
string host = "uxx.ac.uk";
using (var client = new SshClient(host, user, pass))
{
client.Connect();
var cmd = client.CreateCommand("echo 123");
var result = await Task<string>.Factory.FromAsync(
cmd.BeginExecute,
cmd.EndExecute
);
Console.WriteLine(result);
client.Disconnect();
}
}
}
}
我會親自創建一個擴展方法來執行此轉換并使用它,因為 async/await 是當今 C# 中異步編程的標準方法。
幸運的是,已經有一個nuget 包可以滿足您的要求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449950.html
標籤:C#
上一篇:播種-添加用戶角色
