private Ping pinger = new Ping();
private async void buttonPing_Click(object sender, EventArgs e)
{
try
{
PingReply reply = await pinger.SendPingAsync("66.99.66.99", 30000); //Ждём ответа 30 секунд
textBox1.AppendText(reply.Status.ToString() + Environment.NewLine);
}
catch (Exception exception)
{
textBox1.AppendText("Сработал exception: " + exception.Message + Environment.NewLine);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
pinger.SendAsyncCancel();
textBox1.AppendText("Отмена" + Environment.NewLine);
}
public Task<PingReply> SendPingAsync(string host, int timeout, CancellationToken cancelToken)
{
TaskCompletionSource<PingReply> tcs = new TaskCompletionSource<PingReply>();
if (cancelToken.IsCancellationRequested)
tcs.TrySetCanceled();
else
{
using (Ping ping = new Ping())
{
ping.PingCompleted += (object sender, PingCompletedEventArgs e) =>
{
if (!cancelToken.IsCancellationRequested)
{
if (e.Cancelled)
tcs.TrySetCanceled();
else if (e.Error != null)
tcs.TrySetException(e.Error);
else
tcs.TrySetResult(e.Reply);
}
};
cancelToken.Register(() => {tcs.TrySetCanceled();});
ping.SendAsync(host, timeout, null);
}
};
return tcs.Task;
}