Is there no build-in way to cancel a UdpClient.ReceiveAsync() method?

Viewed 206

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?

1 Answers

This feature has been added in .NET 6:

https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient.receiveasync?view=net-6.0#system-net-sockets-udpclient-receiveasync(system-threading-cancellationtoken)

I recently ran into this exact problem on a .Net Core 3.1 project; no good way around it other than through accessing the socket directly (UdpClient.Client), but it's nice to have it available in. NET 6, as many projects can (and will) be upgraded.

Here is the relevant discussion on GitHub, in case you can't upgrade yet:

https://github.com/dotnet/runtime/issues/921#issuecomment-498299946

Related