1

There is a similar question When should I use UdpClient.BeginReceive? When should I use UdpClient.Receive on a background thread? On that post Marc Gravell wrote "Another advantage of the async approach is that you can always get the data you need, queue another async fetch, and then process the new data on the existing async thread, giving some more options for parallelism (one reading, one processing)."

Would you be able to give me an example of what you mean with this?

My problem is that I am listening to UDP packets but I don't have time to process them in the receiving thread as I want to return to my Receive as soon as possible as to not lose any packets in the meanwhile (being that the socket will drop any packets I don't receive, being that it isn't TCP) what would be the best way to do this?

Community
  • 1
  • 1
user398482
  • 117
  • 2
  • 7

1 Answers1

1

With asynchronous IO, you can return to your caller as soon as you start the IO process. Because the nature of IO bound work is done asynchronously via the operating system, we can take advantage of this.

When you use blocking api such as UdpClient.Recieve on a different thread in order to keep your application responsive that thread will mostly block waiting for the UdpClient to complete its recieve method. With async IO, as mark said, you can free the thread until the IO operation completes and do different work in the meanwhile.

For example, we can use UdpClient.RecieveAsync, which returns a Task<UdpRecieveResult>. Because a task is awaitable (see this for more on awaitables), we can take advantage of async io:

public async Task RecieveAndDoWorkAsync()
{
     var udpClient = new UdpClient(); // Initialize client

     var recieveTask = udpclient.RecieveAsync();

     // Do some more work

     // Wait for the operation to complete, meanwhile returning control to tge calling method (without creating any new threads)
     await recieveTask  
}
Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321