PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How to stop a UdpClient?

 October 22, 2022     .net, c#, sockets     No comments   

Issue

I'm listening to a UDP socket by using an UdpClient:

UdpClient udpClient = new(new IPEndPoint(myLocalAddress, 12345));
udpClient.Receive();

Indeed, this blocks. Because of this, I moved this code in a separate Task.

On a change of the network, I will stop no longer needed UdpClients. For this, I use the NetworkChange.NetworkAddressChanged event.

How can I stop the listening of the UdpClients? The UdpClient.Receive method does not allow a CancellationToken.😗

I also tried to use a Socket directly by using Socket.Receive(datagram). But I can't stop this too.

Both ways do not stop, even the IP address is no longer present, because the network gone.


Solution

You can use the async version of receive (UdpClient.ReceiveAsync). This should accept a Cancellation token in .net 6 (but not in .net-core 3.1 and earlier)



Answered By - Jeanot Zubler
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing