Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Socket Asynchronous Calls


Socket Asynchronous Calls


In the last few columns I have written about asynchronous calls in the .NET framework. .NET allows you to call any method asynchronously through a delegate; however, some .NET classes are based upon Win32 functions, and some of these can be called through native asynchronous mechanisms. In the last column, I described how the FileStream class gives access to the Win32 file access methods and provides methods that access those methods asynchronously through an overlapped file access. In this column, I will describe how the NetworkStream class accesses the Windows asynchronous socket methods.

The NetworkStream class is a wrapper around the Socket class; in effect, it implements the Stream methods in terms of a Socket. So NetworkStream.BeginRead just delegates to Socket.BeginReceive and EndRead delegates to EndReceive (and the same can be said for the Write methods delegating to the appropriate Socket Send methods). Thus, the main work of NetworkStream is actually performed by the Socket class.

In the previous column I mentioned that FileStream buffering complicated the asynchronous calls because a request for data could be satisfied partially by data already read in the read buffer. This is not the case for NetworkStream because this class is not buffered and any buffering is carried out further down the IP stack by the Windows socket library. This means that the asynchronous calls are quite straightforward in their implementation.

So shifting attention to the Socket class, it's worth pointing out that the Windows socket library is initialized by the static constructor with a call to WSAStartup. A static constructor is guaranteed to be called before the type is used and, in practice, it occurs just before the first instance is created. The static constructor checks the type of the operating system and whether a version of NT is used (NT4, Windows 2000, XP, or Windows 2003), then the code can use IO Completion Ports. If Win9x is used, then the code uses overlapped IO and the completion is indicated by the state of an event.

To use an IO Completion Port, the Socket class binds the socket to a ThreadPool thread (through a call to BindHandle) and the callback function is OverlappedAsyncResult.CompletionPortCallback. The OverlappedAsyncResult is the implementation of IAsyncResult that is returned from the BeginReceive or BeginSend. Once the binding to the IO Completion Port has occurred, the async method then calls WSARecv or WSASend, passing an OVERLAPPED structure created from a NativeOverlapped object.

The CompletionPortCallback method is called when the IO call has completed, and this method is passed an OVERLAPPED structure that is converted back to a NativeOverlapped object. This object will have the OverlappedAsyncResult object created when the async call is started and, through this object, CompletionPortCallback can invoke the user provided callback method. Thus, the callback method that is passed to BeginRead or BeginWrite is called on the ThreadPool thread through the IO Completion port binding.

If a completion port is not used, then after WSARecv (or WSASend) is called, the event handle, a delegate, and the OverlappedAsyncResult object is passed to ThreadPool.RegisterWaitForSingleObject. When the overlapped IO has completed, the event will be signaled and the ThreadPool thread will call the delegate passing it the OverlappedAsyncResult object as the state object. The delegate method is OverlappedCallback, which uses the OverlappedAsyncResult object to access and invoke the user's callback method. Again, the callback method is called on a ThreadPool thread.

The EndReceive and EndSend methods are pretty dull; they do not have to copy any data because for the read operation, the user's buffer is passed through BeginReceive. However, these methods do have one interesting aspect-they increment the performance counters that track the number of packets that have been sent or received. So you should always call the EndReceive and EndSend methods to ensure that the performance counters are correctly adjusted.


Richard Grimes speaks at conferences and writes extensively on .NET, COM, and COM+. He is the author of Developing Applications with Visual Studio .NET (Addison-Wesley, 2002). If you have comments about this topic, Richard can be reached at [email protected].



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.