[英]Is there a better way than Thread.Sleep() in ASP.NET API? See scenario below
我正在使用 ASP.NET 核心 Web API 构建一个 web 应用程序。它用于 SSH 与 Linux 服务器的通信,因此我必须等待服务器响应。 现在我正在使用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();
}
}
}
}
您可以使用asynch.AsyncWaitHandle.WaitOne();
而不是显式while
循环来实现相同的行为。
或者,您可以使用Task.Factory.FromAsync
将其转换为可等待的Task
。
您的代码看起来像这样:
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();
}
}
}
}
我个人会创建一个扩展方法来执行此转换和 go,因为 async/await 是当今 C# 中异步编程的标准方法。
幸运的是,已经有一个nuget package可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.