System.Net 类的最佳实践Best Practices for System.Net Classes

以下建议有助于你充分利用 System.Net 中包含的类:The following recommendations will help you use the classes contained in System.Net to their best advantage:

  • 对于传输层安全性 (TLS) 最佳做法,请参阅 .NET Framework 中的传输层安全性 (TLS) 最佳做法For Transport Layer Security (TLS) best practices, see Transport Layer Security (TLS) best practices with .NET Framework.

  • 要转换到子代类,请尽可能使用 WebRequestWebResponse,而不是使用类。Use WebRequest and WebResponse whenever possible instead of type casting to descendant classes. 使用 WebRequest 和 WebResponse 的应用程序,无需大范围修改代码,便可充分利用新的 Internet 协议 。Applications that use WebRequest and WebResponse can take advantage of new Internet protocols without needing extensive code changes.

  • 用 System.Net 类编写在服务器上运行的 ASP.NET 应用程序时,从性能的角度来看,使用 GetResponseGetResponseStream 异步方法要更好些。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.

  • 对 Internet 资源开放的连接数会对网络性能和吞吐量产生显著的影响。The number of connections opened to an Internet resource can have a significant impact on network performance and throughput. 默认情况下,System.Net 在每个主机的每个应用程序中使用两个连接。System.Net uses two connections per application per host by default. 为应用程序在 ServicePoint 中设置 ConnectionLimit 属性,可为特定主机增加此连接数。Setting the ConnectionLimit property in the ServicePoint for your application can increase this number for a particular host. 设置 ServicePointManager.DefaultPersistentConnectionLimit 属性可为所有主机提高此默认设置。Setting the ServicePointManager.DefaultPersistentConnectionLimit property can increase this default for all hosts.

  • 编写套接字级别协议时,尝试尽可能使用 TcpClientUdpClient 编写,而不是直接写入 Socket 中。When writing socket-level protocols, try to use TcpClient or UdpClient whenever possible instead of writing directly to a Socket. 这两个客户端类封装了 TCP 和 UDP 套接字的创建,因此无需处理此连接的详细信息。These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection.

  • 若要访问需要凭据的站点,请使用 CredentialCache 类创建凭据缓存,而非为每个站点提供请求。When accessing sites that require credentials, use the CredentialCache class to create a cache of credentials rather than supplying them with every request. 使用 CredentialCache 类可搜索缓存,查找符合请求的合适凭据,如此,你便无需基于 URL 创建和提供凭据。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.

请参阅See also