Answer the question
In order to leave comments, you need to log in
Is it possible in C# to cancel a Ping?
It would seem that there is a SendAsyncCancel() method. However, we write code
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);
}
Answer the question
In order to leave comments, you need to log in
Found a solution. Works great. I did not check for resource cleanup.
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question