-
StackOverflow 文档
-
C# Language 教程
-
任务并行库
-
PingUrl 的异步版本
static void Main(string[] args)
{
string url = "www.stackoverflow.com";
var pingTask = PingUrlAsync(url);
Console.WriteLine($"Waiting for response from {url}");
Task.WaitAll(pingTask);
Console.WriteLine(pingTask.Result);
}
static async Task<string> PingUrlAsync(string url)
{
string response = string.Empty;
var ping = new System.Net.NetworkInformation.Ping();
var result = await ping.SendPingAsync(url);
await Task.Delay(5000); //simulate slow internet
if (result.Status == System.Net.NetworkInformation.IPStatus.Success)
{
response = $"{url} is online";
}
return response;
}