Condividi tramite


Best Practices for System.Net Classes

The following recommendations will help you use the classes contained in System.Net to their best advantage:

  • Use WebRequest and WebResponse whenever possible instead of type casting to descendant classes. Applications that use WebRequest and WebResponse can take advantage of new Internet protocols without needing extensive code changes.

  • When writing ASP.NET applications that run on a server using the System.Net classes, it is often better, from a performance standpoint, to use the asynchronous methods for GetResponse and GetResponseStream.

  • The number of connections opened to an Internet resource can have a significant impact on network performance and throughput. System.Net uses two connections per application per host by default. Setting the ConnectionLimit property in the ServicePoint for your application can increase this number for a particular host. Setting the ServicePointManager.DefaultPersistentConnectionLimit property can increase this default for all hosts.

  • When writing socket-level protocols, try to use TCPClient or UDPClient whenever possible instead of writing directly to a Socket. These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection.

  • When accessing sites that require credentials, use the CredentialCache class to create a cache of credentials rather than supplying them with every request. The CredentialCache class searches the cache to find the appropriate credential to present with a request, relieving you of the responsibility of creating and presenting credentials based on the URL.

Vedere anche

Altre risorse

Network Programming