Use SendPingAsync instead of Send
inside another task:
static async Task Main(string[] args)
{
using(var pinger = new Ping())
{
while(someCondition)
{
var reply=await pinger.SendPingAsync("www.google.om", 1200);
var pingable = reply.Status == IPStatus.Success;
Console.WriteLine(pingable);
//Wait for 1 second
await Task.Delay(1000);
}
}
Console.WriteLine("FINISH");
}
Or
static async Task Main(string[] args)
{
using(var pinger = new Ping())
{
while(someCondition)
{
await ping(pinger);
//Wait for 1 second
await Task.Delay(1000);
}
}
Console.WriteLine("FINISH");
}
static async Task ping(Ping pinger)
{
var reply=await pinger.SendPingAsync("www.google.om", 1200);
var pingable = reply.Status == IPStatus.Success;
Console.WriteLine(pingable);
}
The original code doesn't work because nothing awaits for the task started with Task.Run
to complete, so the application terminates immediately. There's no need to use Task.Run
though, because Ping
has the asynchronous SendPingAsync
class