Async, non-blocking networking
It should be evident by now that you must ensure that all non-instantaneous operations in your code are a potential performance issue. Slow operations can block a process from continuing. File I/O is one of the areas where this is appropriate. Networking is even slower than that. So, everything that we can do asynchronously should be implemented that way.
The good news is that most classes dealing with networking have asynchronous versions of their methods. The bad news is that for Socket
, it is not as straightforward as you might have hoped. But do not worry: we will tackle this soon!
Making asynchronous calls
In the previous sample, we used the static Dns
class to get information about the address of the NTP server. We called GetHostEntry()
, which is a synchronous blocking call. We can fix that quite easily: Dns
has asynchronous versions of those methods. We can rewrite the call to look like this:
var addresses = await Dns.GetHostEntryAsync...