I have the following method listening to UDP broadcasts:
private async Task ReciveBroadCast()
{
var recv = await udpReceiver.ReceiveAsync();
var remoteEndPoint = recv.RemoteEndPoint;
string message = Encoding.ASCII.GetString(recv.Buffer); //TODO: Do something with this message
var answer = "ok";
var answerBuffer = Encoding.UTF8.GetBytes(answer);
udpReceiver.Send(answerBuffer, 2, remoteEndPoint);
}
Listening to the broadcasts gets started by the user pressing a button. I would also like to be able to stop listening, however there seems to be no way of cancelling the ReceiveAsync()
method.
The only answer I could find so far is from this post: How to to make UdpClient.ReceiveAsync() cancelable?
I was wondering if I missed a better way to do this (since the linked post is quite a few years old)? Or maybe there is a way to generally cancel async methods immediately if a Cancellation Token can't be checked periodically?