This project has moved. For the latest updates, please go here.

Explain the complete execution of Nito.Async.Sockets.ClientTcpSocketImpl.ConnectAsync(IPEndPoint server) method

Jun 14, 2010 at 12:28 PM

i read this power library, but confused to understand the execution Nito.Async.Sockets.ClientTcpSocketImpl.ConnectAsync(IPEndPoint server) method

public void ConnectAsync(IPEndPoint server)
{
    Socket.BeginConnect(server, Sync.SynchronizeAsyncCallback((asyncResult) =>
	{
	    Sync.InvokeAndCallback(() => Socket.EndConnect(asyncResult),
		ConnectCompleted, null);
	}), null);
}

i run "LoweLevelClient" windows form application in debug mode and try to understand but confused the execution of ConnectAsync method

can any one explain the execution of this method.

Coordinator
Jun 16, 2010 at 4:39 AM

First, note the comments at the top of the file: "There are two layers of classes defined in this file: the lower layer (ending in *Impl) provides a thin translation from IAsyncResult notifications to event-based notifications, including thread synchronization..." and for the class: "Provides a wrapper around a Socket, translating the IAsyncResult-based notifications to event-based notifications, including thread synchronization. This is used for client sockets." So, the purpose of this method is to provide an event-based API for the IAsyncResult BeginConnect/EndConnect methods.

This method has a functional structure, so it is easiest to understand if you start from the "innermost" call and work your way outwards.

ConnectCompleted is the "Delegate to invoke when the connect operation completes." Sync.InvokeAndCallback will call Socket.EndConnect, and then call ConnectCompleted with arguments indicating success (unless Socket.EndConnect threw an exception, in which case Sync.InvokeAndCallback will call ConnectCompleted with arguments indicating the error). All of this is wrapped into a single delegate which takes an IAsyncResult parameter. Sync.SynchronizeAsyncCallback takes this delegate and makes it run in the correct thread. Finally, BeginConnect kicks it all off by starting the Connect operation.

When the function actually executes, things happen in the reverse order.

BeginConnect starts the Connect operation. When the Connect operation completes, the delegate returned by Sync.SynchronizeAsyncCallback is invoked, which marshals the rest of the code back to the original thread. This code then calls Sync.InvokeAndCallback, which calls EndConnect (passing the IAsyncResult). If EndConnect succeeds, then ConnectCompleted is called with arguments indicating success; if EndConnect throws an exception, then ConnectCompleted is called with arguments indicating the error.

       -Steve