Microsoft has a good example of an asynchronous TCP server. It takes a little to wrap your head around you. It was a few hours of my time before I could create a basic TCP structure for my own program based on this example.
http://msdn.microsoft.com/en-us/library/fx6588te.aspx
The logic of the program looks something like this. There is one thread that calls listener.BeginAccept and then blocks allDone.WaitOne. BeginAccept is an asynchronous call that is uploaded to threadpool and handled by the OS. When a new connection arrives, the OS calls the callback method passed with BeginAccept. This method exposes allDone so that the main listening thread knows that it can listen again. The callback method is just a transient method and continues to call another asynchronous call to receive data.
The callback method provided by ReadCallback is the main “loop” of work (actually recursive asynchronous calls) for asynchronous calls. I use the term "loop" loosely because each method actually calls termination, but not until the next asynchronization method is called. In fact, you have a bunch of asynchronous calls that all call each other, and you pass in your "state" object. This object is your own object, and you can do whatever you want with it.
Each callback method gets only two things returned when the OS calls your method:
1) A socket object representing a connection
2) The state object that you use for your logic
With the state object and the socket object, you can efficiently process your “connections” asynchronously. The OS is very good at that.
In addition, since your main loop blocks waiting for a connection and unloads these connections into the thread pool through asynchronous calls, it no longer works in most cases. The thread pool for your sockets is handled by the OS through the completion ports, so they do not do any real work until the data appears. A very small processor is used, and it is effectively threaded through the thread pool.
PS From what I understand, you don’t want to do the hard work with these methods just by handling data movement. Since the thread pool is the pool for your network I / O and is used by other programs, you must offload any hard work through threads / tasks / asynchronous process so as not to cause the socket thread pool to fail.
PPS I did not find a way to close the listening connection, except to simply dispose of the "listener". Since the asynchronous call to beginListen is called, this method will never return until the connection is made, which means that I cannot tell it to stop until it returns. I think I'll post a question about MSDN on it. and a link if I get a good answer.