-
Notifications
You must be signed in to change notification settings - Fork 30
Performance
Currently there are three approaches with sockets in .NET: synchronous (blocking) calls, asynchronous calls (APM) and High Performance socket (SocketAsyncEventArgs). Each one with pros and cons.
-
Synchronous (blocking) calls: In this model, Connect, Send and Receive are blocking methods, that means that they block the executing thread until the operation finished when are invoked. For that reason, if we want to continue sending and receiving data to/from different peers, we need to use threads and sinchronize access to shared resources. Life is simplier without threads, moreover this model doesn't scale very well because 100 peers mean 100 threads and the continuous context switching, and the waits produced by the mutual exclusions degrade the application performance. In other words, this model is not suitable for applications with a lot of connections like peer-to-peer applications.
-
Asynchronous Programming Model (APM): This model is supported for .NET sinceever and is very popular even today. It consists of pairs of BeginXXX/EndXXX methods that use a callback method which is invoked once the operation (conecting, sending, receiving) finishes. There is no blocking here however, the callback is invoked from a different thread that that invoked the BeginXXX so, some synchronization is required. Moreover, with .NET framework 4+ we can simplify the usage throught TaskFactory.FromAsync that is easier and more elegant. This apporach is very good and there are lots of very well known and well done software that use it (RavenDb is an example). Nevertheless, the performance has been improved in .NET 3.5 with the new High Performance Sockets.
-
High Performance Sockets: .NET framework 3.5 introduces a alternative new pattern for handling sockets, specially designed for applications that requires high performance. This pattern, even when simple, doesn't come without some details that are worth abtract away. For example, its requires a pool of SocketAsyncEventArg instances to reuse. Peer2Net uses this pattern.