.NET Framework 中的新增功能What's new in the .NET Framework

本文总结了以下版本的 .NET Framework 中的主要新功能和改进:This article summarizes key new features and improvements in the following versions of the .NET Framework:

本文不提供有关每项新增功能的完整信息,并有可能会发生更改。This article does not provide comprehensive information about each new feature and is subject to change. 有关 .NET Framework 的常规信息,请参阅入门For general information about the .NET Framework, see Getting Started. 有关支持的平台,请参阅系统要求For supported platforms, see System Requirements. 有关下载链接和安装说明,请参阅安装指南For download links and installation instructions, see Installation Guide.

备注

.NET Framework 团队还发布 NuGet 带外功能以扩展平台支持并引入新功能,如不可变集合和启用了 SIMD 的矢量类型。The .NET Framework team also releases features out of band with NuGet to expand platform support and to introduce new functionality, such as immutable collections and SIMD-enabled vector types. 有关详细信息,请参阅其他类库和 API 以及 .NET Framework 和带外版本For more information, see Additional Class Libraries and APIs and The .NET Framework and Out-of-Band Releases. 请参阅用于 .NET Framework 的 完整 NuGet 包列表See a complete list of NuGet packages for the .NET Framework.

.NET Framework 4.8 简介Introducing .NET Framework 4.8

.NET Framework 4.8 在 .NET Framework 4.x 早期版本的基础之上构建而成,新增了许多修补程序和功能,同时很好地保持了产品的稳定性。.NET Framework 4.8 builds on previous versions of the .NET Framework 4.x by adding many new fixes and several new features while remaining a very stable product.

下载和安装 .NET Framework 4.8Downloading and installing .NET Framework 4.8

可以从下列位置下载 .NET Framework 4.8:You can download .NET Framework 4.8 from the following locations:

可以在 Windows 10、Windows 8.1、Windows 7 SP1 和对应的服务器平台(版本不低于 Windows Server 2008 R2 SP1)上安装 .NET Framework 4.8。.NET Framework 4.8 can be installed on Windows 10, Windows 8.1, Windows 7 SP1, and the corresponding server platforms starting with Windows Server 2008 R2 SP1. 可以使用 Web 安装程序或脱机安装程序来安装 .NET Framework 4.8。You can install .NET Framework 4.8 by using either the web installer or the offline installer. 适用于大多数用户的建议方法是使用 Web 安装程序。The recommended way for most users is to use the web installer.

可以通过安装 .NET Framework 4.8 开发人员工具包,在 Visual Studio 2012 或更高版本中定位 .NET Framework 4.8。You can target .NET Framework 4.8 in Visual Studio 2012 or later by installing the .NET Framework 4.8 Developer Pack.

.NET Framework 4.8 中的新增功能What's new in .NET Framework 4.8

.NET Framework 4.8 在以下几个领域引入了新功能:.NET Framework 4.8 introduces new features in the following areas:

改进了辅助功能,使应用程序能为辅助技术的用户提供最佳体验,这仍是 .NET Framework 4.8 的重点。Improved accessibility, which allows an application to provide an appropriate experience for users of Assistive Technology, continues to be a major focus of .NET Framework 4.8. 有关 .NET Framework 4.8 中辅助功能改进的信息,请参阅 .NET Framework 中辅助功能的新增功能For information on accessibility improvements in .NET Framework 4.8, see What's new in accessibility in the .NET Framework.

基类Base classes

减少 FIPS 对加密的影响Reduced FIPS impact on Cryptography. 在 .NET framework 的早期版本中,当在“FIPS 模式”下配置系统加密库时,SHA256Managed 等托管加密提供程序类会引发 CryptographicExceptionIn previous versions of the .NET Framework, managed cryptographic provider classes such as SHA256Managed throw a CryptographicException when the system cryptographic libraries are configured in “FIPS mode”. 引发这些异常的原因是加密提供程序类的托管版本尚未进行 FIPS(联邦信息处理标准)140-2 认证,这与系统加密库不同。These exceptions are thrown because the managed versions of the cryptographic provider classes, unlike the system cryptographic libraries, have not undergone FIPS (Federal Information Processing Standards) 140-2 certification. 由于几个开发人员使其开发计算机处于 FIPS 模式,因此通常会在生产系统中引发异常。Because few developers have their development machines in FIPS mode, the exceptions are commonly thrown in production systems.

默认情况下,在面向 .NET Framework 4.8 的应用程序中,以下托管加密类在这种情况下不再引发 CryptographicExceptionBy default in applications that target .NET Framework 4.8, the following managed cryptography classes no longer throw a CryptographicException in this case:

相反,这些类会将加密操作重定向到系统加密库。Instead, these classes redirect cryptographic operations to a system cryptography library. 此更改可有效地删除开发人员环境和生产环境之间可能令人混淆的差异,并使本机组件和托管组件采用相同的加密策略运行。This change effectively removes a potentially confusing difference between developer environments and production environments and makes native components and managed components operate under the same cryptographic policy. 依赖于这些异常的应用程序可以通过将 AppContext 开关 Switch.System.Security.Cryptography.UseLegacyFipsThrow 设置为 true 来还原以前的行为。Applications that depend on these exceptions can restore the previous behavior by setting the AppContext switch Switch.System.Security.Cryptography.UseLegacyFipsThrow to true. 有关详细信息,请参阅托管加密类不会在 FIPS 模式下引发 CryptographyExceptionFor more information, see Managed cryptography classes do not throw a CryptographyException in FIPS mode.

使用 ZLib 的更新版本Use of updated version of ZLib

从 .NET Framework 4.5 开始,clrcompression.dll 程序集使用 ZLib(即,数据压缩的本机外部库),以便提供 deflate 算法实现。Starting with .NET Framework 4.5, the clrcompression.dll assembly uses ZLib, a native external library for data compression, in order to provide an implementation for the deflate algorithm. 在 .NET Framework 4.8 中,clrcompression.dll 更新为使用 ZLib 版本 1.2.11,其中包括几个主要的改进和修补程序。The .NET Framework 4.8, clrcompression.dll is updated to use ZLib Version 1.2.11, which includes several key improvements and fixes.

Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)

ServiceHealthBehavior 简介Introduction of ServiceHealthBehavior

运行状况终结点由业务流程工具广泛使用以基于其运行状况状态来管理服务。Health endpoints are widely used by orchestration tools to manage services based on their health status. 运行状况检查还可由监视工具使用以跟踪并提供有关服务的可用性和性能的通知。Health checks can also be used by monitoring tools to track and provide notifications about the availability and performance of a service.

ServiceHealthBehavior 是一个 WCF 服务行为,该行为可扩展 IServiceBehaviorServiceHealthBehavior is a WCF service behavior that extends IServiceBehavior. 添加到 ServiceDescription.Behaviors 集合后,服务行为会执行以下操作:When added to the ServiceDescription.Behaviors collection, a service behavior does the following:

  • 返回带有 HTTP 响应代码的服务运行状况状态。Returns service health status with HTTP response codes. 可以在查询字符串中指定 HTTP/GET 运行状况探测请求的 HTTP 状态代码。You can specify in a query string the HTTP status code for a HTTP/GET health probe request.

  • 发布有关服务运行状况的信息。Publishes information about service health. 服务特定的详细信息,包括可以使用带有 ?health 查询字符串的 HTTP/GET 请求显示的服务状态、限制计数和容量。Service-specific details, including service state, throttle counts, and capacity can be displayed by using an HTTP/GET request with the ?health query string. 对行为不正常的 WCF 服务进行故障排除时,可以轻松访问此类信息则很重要。Ease of access to such information is important when troubleshooting a misbehaving WCF service.

可通过两种方式公开运行状况终结点并发布 WCF 服务运行状况信息:There are two ways to expose the health endpoint and publish WCF service health information:

  • 通过代码。Through code. 例如:For example:

    ServiceHost host = new ServiceHost(typeof(Service1),
                       new Uri("http://contoso:81/Service1"));
    ServiceHealthBehavior healthBehavior =
        host.Description.Behaviors.Find<ServiceHealthBehavior>();
    healthBehavior ??= new ServiceHealthBehavior();
    host.Description.Behaviors.Add(healthBehavior);
    
    Dim host As New ServiceHost(GetType(Service1),
                New Uri("http://contoso:81/Service1"))
    Dim healthBehavior As ServiceHealthBehavior =
       host.Description.Behaviors.Find(Of ServiceHealthBehavior)()
    If healthBehavior Is Nothing Then
       healthBehavior = New ServiceHealthBehavior()
    End If
    host.Description.Behaviors.Add(healthBehavior)
    
  • 通过使用配置文件。By using a configuration file. 例如:For example:

    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceHealth httpsGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    

可以使用查询参数(例如,OnServiceFailureOnDispatcherFailureOnListenerFailureOnThrottlePercentExceeded)查询服务的运行状况状态,并且可以为每个查询参数指定 HTTP 响应代码。A service's health status can be queried by using query parameters such as OnServiceFailure, OnDispatcherFailure, OnListenerFailure, OnThrottlePercentExceeded), and an HTTP response code can be specified for each query parameter. 如果省略了查询参数的 HTTP 响应代码,则默认使用 503 HTTP 响应代码。If the HTTP response code is omitted for a query parameter, a 503 HTTP response code is used by default. 例如:For example:

  • OnServiceFailure:https://contoso:81/Service1?health&OnServiceFailure=450OnServiceFailure: https://contoso:81/Service1?health&OnServiceFailure=450

    ServiceHost.State 大于 CommunicationState.Opened 时,将返回 450 HTTP 响应状态代码。A 450 HTTP response status code is returned when ServiceHost.State is greater than CommunicationState.Opened. 查询参数和示例:Query parameters and examples:

  • OnDispatcherFailure:https://contoso:81/Service1?health&OnDispatcherFailure=455OnDispatcherFailure: https://contoso:81/Service1?health&OnDispatcherFailure=455

    当任意通道调度程序的状态大于 CommunicationState.Opened 时,将返回 455 HTTP 响应状态代码。A 455 HTTP response status code is returned when the state of any of the channel dispatchers is greater than CommunicationState.Opened.

  • OnListenerFailure:https://contoso:81/Service1?health&OnListenerFailure=465OnListenerFailure: https://contoso:81/Service1?health&OnListenerFailure=465

    当任意通道侦听器的状态大于 CommunicationState.Opened 时,将返回 465 HTTP 响应状态代码。A 465 HTTP response status code is returned when the state of any of the channel listeners is greater than CommunicationState.Opened.

  • OnThrottlePercentExceeded:https://contoso:81/Service1?health&OnThrottlePercentExceeded= 70:350,95:500OnThrottlePercentExceeded: https://contoso:81/Service1?health&OnThrottlePercentExceeded= 70:350,95:500

    指定触发响应及其 HTTP 响应代码 {200 – 599} 的百分比 {1 – 100}。Specifies the percentage {1 – 100} that triggers the response and its HTTP response code {200 – 599}. 在此示例中:In this example:

    • 如果百分比大于 95,则返回 500 HTTP 响应代码。If the percentage is greater than 95, a 500 HTTP response code is returned.

    • 如果百分比介于 70 和 95 之间,则返回 350。If the percentage or between 70 and 95, 350 is returned.

    • 否则将返回 200。Otherwise, 200 is returned.

服务运行状况状态可以通过指定查询字符串(如 https://contoso:81/Service1?health)以 HTML 格式显示,或通过指定查询字符串(如 https://contoso:81/Service1?health&Xml)以 XML 格式显示。The service health status can be displayed either in HTML by specifying a query string like https://contoso:81/Service1?health or in XML by specifying a query string like https://contoso:81/Service1?health&Xml. 查询字符串(如 https://contoso:81/Service1?health&NoContent)返回空 HTML 页。A query string like https://contoso:81/Service1?health&NoContent returns an empty HTML page.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

高 DPI 增强功能High DPI enhancements

在 .NET Framework 4.8 中,WPF 添加了对按监视器 V2 DPI 感知和混合模式 DPI 缩放的支持。In .NET Framework 4.8, WPF adds support for Per-Monitor V2 DPI Awareness and Mixed-Mode DPI scaling. 有关高 DPI 开发的其他信息,请参阅在 Windows 上开发高 DPI 桌面应用程序See High DPI Desktop Application Development on Windows for additional information about high DPI development.

.NET framework 4.8 改进了对支持混合模式 DPI 缩放的平台上的高 DPI WPF 应用程序中的寄宿 HWND 和 Windows 窗体互操作的支持(从 Windows 10 2018 年 4 月更新开始)。.NET Framework 4.8 improves support for hosted HWNDs and Windows Forms interoperation in High-DPI WPF applications on platforms that support Mixed-Mode DPI scaling (starting with Windows 10 April 2018 Update). 通过调用 SetThreadDpiHostingBehaviorSetThreadDpiAwarenessContext 将寄宿 HWND 或 Windows 窗体控件创建为混合模式 DPI 缩放窗口时,它们可以托管在按监视器 V2 WPF 应用程序中,并且相应地调整大小和缩放。When hosted HWNDs or Windows Forms controls are created as Mixed-Mode DPI-scaled windows by calling SetThreadDpiHostingBehavior and SetThreadDpiAwarenessContext, they can be hosted in a Per-Monitor V2 WPF application and are sized and scaled appropriately. 此类托管内容不以本机 DPI 呈现;相反,操作系统将托管内容缩放到合适大小。Such hosted content is not rendered at the native DPI; instead, the operating system scales the hosted content to the appropriate size. 对按监视器 v2 DPI 感知模式的支持还允许 WPF 控件托管(即,设置为父级)在高 DPI 应用程序的本机窗口中。The support for Per-Monitor v2 DPI awareness mode also allows WPF controls to be hosted (i.e., parented) in a native window in a high-DPI application.

若要启用对混合模式高 DPI 缩放的支持,可以设置以下 AppContext 切换应用程序配置文件:To enable support for Mixed-Mode High DPI scaling, you can set the following AppContext switches the application configuration file:

<runtime>
   <AppContextSwitchOverrides value = "Switch.System.Windows.DoNotScaleForDpiChanges=false; Switch.System.Windows.DoNotUsePresentationDpiCapabilityTier2OrGreater=false"/>
</runtime>

公共语言运行时Common language runtime

.NET Framework 4.8 中的运行时包含以下更改和改进:The runtime in .NET Framework 4.8 includes the following changes and improvements:

JIT 编译器的改进Improvements to the JIT compiler. .NET Framework 4.8 中的实时 (JIT) 编译器基于 .NET Core 2.1 中的 JIT 编译器。The Just-in-time (JIT) compiler in .NET Framework 4.8 is based on the JIT compiler in .NET Core 2.1. 对 .NET Core 2.1 JIT 编译器所做的多个优化和所有 bug 修复都包含在 .NET Framework 4.8 JIT 编译器中。Many of the optimizations and all of the bug fixes made to the .NET Core 2.1 JIT compiler are included in the .NET Framework 4.8 JIT compiler.

NGEN 改进NGEN improvements. 运行时改进了本机映像生成器 (NGEN) 映像的内存管理,以便从 NGEN 映像映射的数据不驻留在内存中。The runtime has improved its memory management for Native Image Generator (NGEN) images so that data mapped from NGEN images are not memory-resident. 这将缩减可受到攻击的外围应用,攻击方法为试图通过修改将执行的内存来执行任意代码。This reduces the surface area available to attacks that attempt to execute arbitrary code by modifying memory that will be executed.

所有程序集的反恶意软件扫描Antimalware scanning for all assemblies. 在 .NET Framework 的早期版本中,运行时使用 Windows Defender 或第三方反恶意软件扫描从磁盘加载的所有程序集。In previous versions of the .NET Framework, the runtime scans all assemblies loaded from disk using either Windows Defender or third-party antimalware software. 但是,从其他源加载的程序集(例如,通过 Assembly.Load(Byte[]) 方法)不会进行扫描,并且可能包含未检测到的恶意软件。However, assemblies loaded from other sources, such as by the Assembly.Load(Byte[]) method, are not scanned and can potentially contain undetected malware. 从 Windows 10 上运行的 .NET Framework 4.8 开始,运行时通过实现反恶意软件扫描界面 (AMSI) 的反恶意软件解决方案来触发扫描。Starting with .NET Framework 4.8 running on Windows 10, the runtime triggers a scan by antimalware solutions that implement the Antimalware Scan Interface (AMSI).

.NET Framework 4.7.2 中的新增功能What's new in .NET Framework 4.7.2

.NET Framework 4.7.2 在以下几个领域新增了功能:.NET Framework 4.7.2 includes new features in the following areas:

.NET Framework 4.7.2 持续关注的重点是辅助功能的改进,使应用程序能为使用辅助技术的用户提供最佳体验。A continuing focus in .NET Framework 4.7.2 is improved accessibility, which allows an application to provide an appropriate experience for users of Assistive Technology. 有关 .NET Framework 4.7.2 中辅助功能改进的信息,请参阅 .NET Framework 中辅助功能的新增功能For information on accessibility improvements in .NET Framework 4.7.2, see What's new in accessibility in the .NET Framework.

基类Base classes

.NET Framework 4.7.2 提供大量的加密增强功能、对 ZIP 存档更好的解压缩支持以及额外的集合 API。.NET Framework 4.7.2 features a large number of cryptographic enhancements, better decompression support for ZIP archives, and additional collection APIs.

RSA.Create 和 DSA.Create 的新重载New overloads of RSA.Create and DSA.Create

利用 DSA.Create(DSAParameters)RSA.Create(RSAParameters) 方法,可以在实例化新的 DSARSA 密钥时提供密钥参数。The DSA.Create(DSAParameters) and RSA.Create(RSAParameters) methods let you supply key parameters when instantiating a new DSA or RSA key. 它们允许你替换如下所示的代码:They allow you to replace code like the following:

// Before .NET Framework 4.7.2
using (RSA rsa = RSA.Create())
{
   rsa.ImportParameters(rsaParameters);
   // Other code to execute using the RSA instance.
}
' Before .NET Framework 4.7.2
Using rsa = RSA.Create()
   rsa.ImportParameters(rsaParameters)
   ' Other code to execute using the rsa instance.
End Using

采用类似如下所示的代码:with code like this:

// Starting with .NET Framework 4.7.2
using (RSA rsa = RSA.Create(rsaParameters))
{
   // Other code to execute using the rsa instance.
}
' Starting with .NET Framework 4.7.2
Using rsa = RSA.Create(rsaParameters)
   ' Other code to execute using the rsa instance.
End Using

DSA.Create(Int32)RSA.Create(Int32) 方法允许生成具有特定密钥大小的 DSARSA 密钥。The DSA.Create(Int32) and RSA.Create(Int32) methods let you generate new DSA or RSA keys with a specific key size. 例如:For example:

using (DSA dsa = DSA.Create(2048))
{
   // Other code to execute using the dsa instance.
}
Using dsa = DSA.Create(2048)
   ' Other code to execute using the dsa instance.
End Using

Rfc2898DeriveBytes 构造函数接受哈希算法名称Rfc2898DeriveBytes constructors accept a hash algorithm name

Rfc2898DeriveBytes 类具有三个带 HashAlgorithmName 参数的构造函数,该参数标识在派生密钥时使用的 HMAC 算法。The Rfc2898DeriveBytes class has three new constructors with a HashAlgorithmName parameter that identifies the HMAC algorithm to use when deriving keys. 与 SHA-1 相比,开发人员应使用基于 SHA-2 的 HMAC,例如 SHA-256,如下面的示例所示:Instead of using SHA-1, developers should use a SHA-2-based HMAC like SHA-256, as shown in the following example:

private static byte[] DeriveKey(string password, out int iterations, out byte[] salt,
                                out HashAlgorithmName algorithm)
{
   iterations = 100000;
   algorithm = HashAlgorithmName.SHA256;

   const int SaltSize = 32;
   const int DerivedValueSize = 32;

   using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, SaltSize,
                                                             iterations, algorithm))
   {
      salt = pbkdf2.Salt;
      return pbkdf2.GetBytes(DerivedValueSize);
   }
}
Private Shared Function DeriveKey(password As String, ByRef iterations As Integer,
                                  ByRef salt AS Byte(), ByRef algorithm As HashAlgorithmName) As Byte()
   iterations = 100000
   algorithm = HashAlgorithmName.SHA256

   Const SaltSize As Integer = 32
   Const  DerivedValueSize As Integer = 32

   Using pbkdf2 = New Rfc2898DeriveBytes(password, SaltSize, iterations, algorithm)
      salt = pbkdf2.Salt
      Return pbkdf2.GetBytes(DerivedValueSize)
   End Using
End Function

临时密钥支持Support for ephemeral keys

PFX 导入可以选择绕过硬盘直接从内存加载私钥。PFX import can optionally load private keys directly from memory, bypassing the hard drive. 如果在 X509Certificate2 构造函数或 X509Certificate2.Import 方法的其中一个重载中指定了新的 X509KeyStorageFlags.EphemeralKeySet 标记,则私钥将加载为临时密钥。 When the new X509KeyStorageFlags.EphemeralKeySet flag is specified in an X509Certificate2 constructor or one of the overloads of the X509Certificate2.Import method, the private keys will be loaded as ephemeral keys. 这能防止密钥在磁盘上可见。This prevents the keys from being visible on the disk. 但是:However:

  • 由于密钥不会保留到磁盘,最好不要将通过此标记加载的证书添加到 X509Store。Since the keys are not persisted to disk, certificates loaded with this flag are not good candidates to add to an X509Store.

  • 以这种方式加载的密钥大多都是通过 Windows CNG 加载的。Keys loaded in this manner are almost always loaded via Windows CNG. 因此,调用方必须通过调用扩展方法访问私钥,例如 cert.GetRSAPrivateKey()Therefore, callers must access the private key by calling extension methods, such as cert.GetRSAPrivateKey(). X509Certificate2.PrivateKey 属性不起作用。The X509Certificate2.PrivateKey property does not function.

  • 由于旧的 X509Certificate2.PrivateKey 属性对证书不起作用,开发人员应在切换至临时密钥之前执行严密的测试。Since the legacy X509Certificate2.PrivateKey property does not work with certificates, developers should perform rigorous testing before switching to ephemeral keys.

PKCS#10 证书签名请求和 X.509 公钥证书的编程式创建Programmatic creation of PKCS#10 certification signing requests and X.509 public key certificates

从 .NET Framework 4.7.2 开始,工作负载可以生成证书签名请求 (CSR),这允许将证书请求生成分阶到现有工具中。Starting with .NET Framework 4.7.2, workloads can generate certificate signing requests (CSRs), which allows certificate request generation to be staged into existing tooling. 这在测试方案中常常很有用。This is frequently useful in test scenarios.

有关详细信息和代码示例,请参阅 .NET 博客中的“PKCS#10 证书签名请求和 X.509 公钥证书的编程式创建”。For more information and code examples, see "Programmatic creation of PKCS#10 certification signing requests and X.509 public key certificates" in the .NET Blog.

新的 SignerInfo 成员New SignerInfo members

从 .NET Framework 4.7.2 开始,SignerInfo 类将公开更多有关签名的信息。Starting with .NET Framework 4.7.2, the SignerInfo class exposes more information about the signature. 你可以检索 System.Security.Cryptography.Pkcs.SignerInfo.SignatureAlgorithm 属性的值,以确定签名者采用的签名算法。You can retrieve the value of the System.Security.Cryptography.Pkcs.SignerInfo.SignatureAlgorithm property to determine the signature algorithm used by the signer. 可以调用 SignerInfo.GetSignature 来获取此签名者的加密签名副本。SignerInfo.GetSignature can be called to get a copy of the cryptographic signature for this signer.

在 CryptoStream 释放后保持包装流打开Leaving a wrapped stream open after CryptoStream is disposed

从 .NET Framework 4.7.2 开始,CryptoStream 类有了一个额外的构造函数可允许 Dispose 不关闭包装流。Starting with .NET Framework 4.7.2, the CryptoStream class has an additional constructor that allows Dispose to not close the wrapped stream. 若要在释放 CryptoStream 实例后保持包装流的打开状态,请调用新的 CryptoStream 构造函数,如下所示: To leave the wrapped stream open after the CryptoStream instance is disposed, call the new CryptoStream constructor as follows:

var cStream = new CryptoStream(stream, transform, mode, leaveOpen: true);
Dim cStream = New CryptoStream(stream, transform, mode, leaveOpen:=true)

DeflateStream 中的解压缩更改Decompression changes in DeflateStream

从 .NET Framework 4.7.2 开始,DeflateStream 类中的解压缩操作的实现变为默认使用本机 Windows API。Starting with .NET Framework 4.7.2, the implementation of decompression operations in the DeflateStream class has changed to use native Windows APIs by default. 通常情况下,这能大大地提高性能。Typically, this results in a substantial performance improvement.

对于面向 .NET Framework 4.7.2 的应用程序,默认启用通过使用 Windows API 进行解压缩的支持。Support for decompression by using Windows APIs is enabled by default for applications that target .NET Framework 4.7.2. 对于面向旧版 .NET Framework 但在 .NET Framework 4.7.2 下运行的应用程序,可以将以下 AppContext 开关添加到应用程序配置文件,从而选择启用此行为:Applications that target earlier versions of .NET Framework but are running under .NET Framework 4.7.2 can opt into this behavior by adding the following AppContext switch to the application configuration file:

<AppContextSwitchOverrides value="Switch.System.IO.Compression.DoNotUseNativeZipLibraryForDecompression=false" />

额外的集合 APIAdditional collection APIs

.NET Framework 4.7.2 将一些新 API 添加到 SortedSet<T>HashSet<T> 类型。.NET Framework 4.7.2 adds a number of new APIs to the SortedSet<T> and HashSet<T> types. 这些方法包括:These include:

ConcurrentDictionary<TKey,TValue> 类包含 AddOrUpdateGetOrAdd 方法的新重载,以便在词典中检索值或添加找不到的值,以及将值添加到词典或者更新已存在的值。The ConcurrentDictionary<TKey,TValue> class includes new overloads of the AddOrUpdate and GetOrAdd methods to retrieve a value from the dictionary or to add it if it is not found, and to add a value to the dictionary or to update it if it already exists.

public TValue AddOrUpdate<TArg>(TKey key, Func<TKey, TArg, TValue> addValueFactory, Func<TKey, TValue, TArg, TValue> updateValueFactory, TArg factoryArgument)

public TValue GetOrAdd<TArg>(TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument)
Public AddOrUpdate(Of TArg)(key As TKey, addValueFactory As Func(Of TKey, TArg, TValue), updateValueFactory As Func(Of TKey, TValue, TArg, TValue), factoryArgument As TArg) As TValue

Public GetOrAdd(Of TArg)(key As TKey, valueFactory As Func(Of TKey, TArg, TValue), factoryArgument As TArg) As TValue

ASP.NETASP.NET

Web 窗体中的依赖项注入支持Support for dependency injection in Web Forms

依赖项注入 (DI) 分离对象和它们的依赖项,使得对象的代码不再仅因依赖项更改而需要进行更改。Dependency injection (DI) decouples objects and their dependencies so that an object's code no longer needs to be changed just because a dependency has changed. 在开发面向 .NET Framework 4.7.2 的 ASP.NET 应用程序时,可以:When developing ASP.NET applications that target .NET Framework 4.7.2, you can:

同站点 cookie 支持Support for same-site cookies

SameSite 防止浏览器将 cookie 和跨站点请求一起发送。SameSite prevents a browser from sending a cookie along with a cross-site request. .NET Framework 4.7.2 添加了一个值为 System.Web.SameSiteMode 枚举成员的 HttpCookie.SameSite 属性。.NET Framework 4.7.2 adds a HttpCookie.SameSite property whose value is a System.Web.SameSiteMode enumeration member. 如果它的值为 SameSiteMode.StrictSameSiteMode.Lax,ASP.NET 将 SameSite 属性添加到 set-cookie 标头。If its value is SameSiteMode.Strict or SameSiteMode.Lax, ASP.NET adds the SameSite attribute to the set-cookie header. SameSite 支持适用于 HttpCookie 对象,以及 FormsAuthenticationSystem.Web.SessionState cookie。SameSite support applies to HttpCookie objects, as well as to FormsAuthentication and System.Web.SessionState cookies.

可以为 HttpCookie 对象设置 SameSite,如下所示:You can set SameSite for an HttpCookie object as follows:

var c = new HttpCookie("secureCookie", "same origin");
c.SameSite = SameSiteMode.Lax;
Dim c As New HttpCookie("secureCookie", "same origin")
c.SameSite = SameSiteMode.Lax

还可以通过修改 web.config 文件,在应用程序级别配置 SameSite cookie:You can also configure SameSite cookies at the application level by modifying the web.config file:

<system.web>
   <httpCookies sameSite="Strict" />
</system.web>

通过修改 Web 配置文件,可以为 FormsAuthenticationSystem.Web.SessionState cookie 添加 SameSite:You can add SameSite for FormsAuthentication and System.Web.SessionState cookies by modifying the web config file:

<system.web>
   <authentication mode="Forms">
      <forms cookieSameSite="Lax">
         <!-- ...   -->
      </forms>
   <authentication />
   <sessionState cookieSameSite="Lax"></sessionState>
</system.web>

网络Networking

HttpClientHandler 属性的实现Implementation of HttpClientHandler properties

.NET Framework 4.7.1 将八个属性添加到了 System.Net.Http.HttpClientHandler 类。.NET Framework 4.7.1 added eight properties to the System.Net.Http.HttpClientHandler class. 不过其中有两个会引发 PlatformNotSupportedExceptionHowever, two threw a PlatformNotSupportedException. .NET Framework 4.7.2 现在为这些属性提供实现。.NET Framework 4.7.2 now provides an implementation for these properties. 这些属性为:The properties are:

SQLClientSQLClient

对 Azure Active Directory 通用身份验证和多重身份验证的支持Support for Azure Active Directory Universal Authentication and Multi-Factor authentication

不断增加的符合性和安全性需求让很多客户需要使用多重身份验证 (MFA)。Growing compliance and security demands require that many customers use multi-factor authentication (MFA). 此外,当前的最佳做法不鼓励在连接字符串中直接包含用户密码。In addition, current best practices discourage including user passwords directly in connection strings. 为了支持这些更改,.NET Framework 4.7.2 通过添加新值“Active Directory Interactive”扩展了 SQLClient 连接字符串,让现有“身份验证”关键字支持 MFA 和 Azure AD 身份验证To support these changes, .NET Framework 4.7.2 extends SQLClient connection strings by adding a new value, "Active Directory Interactive", for the existing "Authentication" keyword to support MFA and Azure AD Authentication. 新的交互式方法支持本机和联合 Azure AD 用户以及 Azure AD 来宾用户。The new interactive method supports native and federated Azure AD users as well as Azure AD guest users. 使用此方法时,SQL 数据库将支持由 Azure AD 施加的 MFA 身份验证。When this method is used, the MFA authentication imposed by Azure AD is supported for SQL databases. 此外,为了遵循安全最佳做法,身份验证流程会请求用户密码。In addition, the authentication process requests a user password to adhere to security best practices.

在以前版本的 .NET Framework 中,SQL 连接只支持 SqlAuthenticationMethod.ActiveDirectoryPasswordSqlAuthenticationMethod.ActiveDirectoryIntegrated 选项。In previous versions of the .NET Framework, SQL connectivity supported only the SqlAuthenticationMethod.ActiveDirectoryPassword and SqlAuthenticationMethod.ActiveDirectoryIntegrated options. 两者都是非交互式 ADAL 协议的一部分,而该协议不支持 MFA。Both of these are part of the non-interactive ADAL protocol, which does not support MFA. 利用新的 SqlAuthenticationMethod.ActiveDirectoryInteractive 选项,SQL 连接可支持 MFA 以及现有身份验证方法(密码和集成身份验证),让用户可以交互式地输入用户密码,而无需将密码存留在连接字符串中。With the new SqlAuthenticationMethod.ActiveDirectoryInteractive option, SQL connectivity supports MFA as well as existing authentication methods (password and integrated authentication), which allows users to enter user passwords interactively without persisting passwords in the connection string.

有关详细信息和示例,请参阅 .NET 博客中的“SQL - Azure AD 通用和多重身份验证支持”。For more information and an example, see "SQL -- Azure AD Universal and Multi-factor Authentication Support" in the .NET Blog.

Always Encrypted 版本 2 的支持Support for Always Encrypted version 2

NET Framework 4.7.2 为基于 enclave 的 Always Encrypted 添加支持。NET Framework 4.7.2 adds supports for enclave-based Always Encrypted. Always Encrypted 的原始版本是客户端加密技术,其中的加密密钥不会离开客户端。The original version of Always Encrypted is a client-side encryption technology in which encryption keys never leave the client. 在基于 enclave 的 Always Encrypted 中,客户端可以选择将加密密钥发送到安全的 enclave,即一个安全的计算实体,该实体可以看作是 SQL Server 的一部分,但 SQL Server 代码无法对其进行篡改。In enclave-based Always Encrypted, the client can optionally send the encryption keys to a secure enclave, which is a secure computational entity that can be considered part of SQL Server but that SQL Server code cannot tamper with. 为了支持基于 enclave 的 Always Encrypted,NET Framework 4.7.2 将以下类型和成员添加到 System.Data.SqlClient 命名空间:To support enclave-based Always Encrypted, .NET Framework 4.7.2 adds the following types and members to the System.Data.SqlClient namespace:

抽象 System.Data.SqlClient.SqlColumnEncryptionEnclaveProvider 类提供了 enclave 提供程序的功能,应用程序配置文件随后会指定该类的具体实现。The application configuration file then specifies a concrete implementation of the abstract System.Data.SqlClient.SqlColumnEncryptionEnclaveProvider class that provides the functionality for the enclave provider. 例如:For example:

<configuration>
  <configSections>
    <section name="SqlColumnEncryptionEnclaveProviders" type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection,System.Data,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"/> 
  </configSections>
  <SqlColumnEncryptionEnclaveProviders>
    <providers>
      <add name="Azure" type="Microsoft.SqlServer.Management.AlwaysEncrypted.AzureEnclaveProvider,MyApp"/>
      <add name="HGS" type="Microsoft.SqlServer.Management.AlwaysEncrypted.HGSEnclaveProvider,MyApp" />
    </providers>
  </SqlColumnEncryptionEnclaveProviders >
</configuration>

基于 enclave 的 Always Encrypted 的基本流是:The basic flow of enclave-based Always Encrypted is:

  1. 用户创建与 SQL Server(支持基于 enclave 的 Always Encrypted)的 AlwaysEncrypted 连接。The user creates an AlwaysEncrypted connection to SQL Server that supported enclave-based Always Encrypted. 驱动程序联系认证服务以确保它连接到正确的 enclave。The driver contacts the attestation service to ensure that it is connecting to right enclave.

  2. enclave 验证成功后,驱动程序将建立与托管在 SQL Server 上的安全 enclave 之间的安全信道。Once the enclave has been attested, the driver establishes a secure channel with the secure enclave hosted on SQL Server.

  3. 在 SQL 连接期间,驱动程序与安全 enclave 共享由客户端授权的加密密钥。The driver shares encryption keys authorized by the client with the secure enclave for the duration of the SQL connection.

Windows Presentation FoundationWindows Presentation Foundation

按源查找 ResourceDictionariesFinding ResourceDictionaries by Source

从 .NET Framework 4.7.2 开始,诊断助手可以找到从给定源 URI 创建的  ResourceDictionariesStarting with .NET Framework 4.7.2, a diagnostic assistant can locate the ResourceDictionaries that have been created from a given source Uri. (此功能通过诊断助手使用,而非生产应用程序。)诊断助手(例如 Visual Studio 的“编辑并继续”)让用户可以编辑 ResourceDictionary 以将更改应用到正在运行的应用程序。 (This feature is for use by diagnostic assistants, not by production applications.) A diagnostic assistant such as Visual Studio’s “Edit-and-Continue” facility lets its user edit a ResourceDictionary with the intent that the changes be applied to the running application. 要实现这一点,其中一个步骤是从被编辑的字典中找到正在运行的应用程序创建的所有 ResourceDictionaries。One step in achieving this is finding all the ResourceDictionaries that the running application has created from the dictionary that’s being edited. 例如,应用程序可以声明某个从给定源 URI 复制内容的 ResourceDictionary:For example, an application can declare a ResourceDictionary whose content is copied from a given source URI:

<ResourceDictionary Source="MyRD.xaml">

编辑 MyRD.xaml   中的原始标记的诊断助手可以使用新功能来找到字典。A diagnostic assistant that edits the original markup in MyRD.xaml can use the new feature to locate the dictionary. 此功能通过新的静态方法 ResourceDictionaryDiagnostics.GetResourceDictionariesForSource 实现。 The feature is implemented by a new static method, ResourceDictionaryDiagnostics.GetResourceDictionariesForSource. 诊断助手使用标识原始标记的绝对 URI 调用新方法,如以下代码所示:The diagnostic assistant calls the new method using an absolute Uri that identifies the original markup, as illustrated by the following code:

IEnumerable<ResourceDictionary> dictionaries = ResourceDictionaryDiagnostics.GetResourceDictionariesForSource(new Uri("pack://application:,,,/MyApp;component/MyRD.xaml"));
Dim dictionaries As IEnumerable(Of ResourceDictionary) = ResourceDictionaryDiagnostics.GetResourceDictionariesForSource(New Uri("pack://application:,,,/MyApp;component/MyRD.xaml"))

该方法返回空的枚举值,除非启用了  VisualDiagnostics 并且设置了 ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO  环境变量。The method returns an empty enumerable unless VisualDiagnostics is enabled and the ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO environment variable is set.

查找 ResourceDictionary 所有者Finding ResourceDictionary owners

从 .NET Framework 4.7.2 开始,诊断助手可以找到给定 ResourceDictionary 的所有者。Starting with .NET Framework 4.7.2, a diagnostic assistant can locate the owners of a given ResourceDictionary. (此功能供诊断助手,而非生产应用程序使用。)每当对 ResourceDictionary 做出更改时,WPF 会自动查找所有可能会受此更改影响的 DynamicResource 引用。 (The feature is for use by diagnostic assistants and not by production applications.) Whenever a change is made to a ResourceDictionary, WPF automatically finds all DynamicResource references that might be affected by the change.

诊断助手(例如 Visual Studio 的“编辑并继续”)可能想对此进行扩展以处理 StaticResource 引用。A diagnostic assistant such as Visual Studio’s “Edit-and-Continue” facility may want extend this to handle StaticResource references. 此过程的第一步是找到字典的所有者,也就是找到其 Resources 属性引用该字典(不管是直接引用,还是通过 ResourceDictionary.MergedDictionaries 属性间接引用)的所有对象。The first step in this process is to find the owners of the dictionary; that is, to find all the objects whose Resources property refers to the dictionary (either directly, or indirectly via the ResourceDictionary.MergedDictionaries property). System.Windows.Diagnostics.ResourceDictionaryDiagnostics 类上实现的三个新的静态方法(每个对应具有 Resources 属性的基类型)支持此步骤:Three new static methods implemented on the System.Windows.Diagnostics.ResourceDictionaryDiagnostics class, one for each of the base types that has a Resources property, support this step:

这些方法返回空的枚举值,除非启用了  VisualDiagnostics 并且设置了 ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO  环境变量。These methods return an empty enumerable unless VisualDiagnostics is enabled and the ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO environment variable is set.

查找 StaticResource 引用Finding StaticResource references

现在,每当一个 StaticResource 引用被解析时,诊断助手都能收到通知。A diagnostic assistant can now receive a notification whenever a StaticResource reference is resolved. (此功能供诊断助手,而非生产应用程序使用。)诊断助手(例如 Visual Studio 的“编辑并继续”)可能想在 ResourceDictionary 中某个资源的值发生更改时更新该资源的所有使用。 (The feature is for use by diagnostic assistants, not by production applications.) A diagnostic assistant such as Visual Studio’s “Edit-and-Continue” facility may want to update all uses of a resource when its value in a ResourceDictionary changes. WPF 为 DynamicResource 引用自动完成此操作,但不会为 StaticResource 引用有意执行该操作。WPF does this automatically for DynamicResource references, but it intentionally does not do so for StaticResource references. 从 .NET Framework 4.7.2 开始,诊断助手可以利用这些通知来查找静态资源的使用情况。Starting with .NET Framework 4.7.2, the diagnostic assistant can use these notifications to locate those uses of the static resource.

该通知由新的 ResourceDictionaryDiagnostics.StaticResourceResolved 事件实现:The notification is implemented by the new ResourceDictionaryDiagnostics.StaticResourceResolved event:

public static event EventHandler<StaticResourceResolvedEventArgs> StaticResourceResolved;
Public Shared Event StaticResourceResolved As EventHandler(Of StaticResourceResolvedEventArgs)

每当运行时解析 StaticResource 引用时,都会引发此事件。This event is raised whenever the runtime resolves a StaticResource reference. StaticResourceResolvedEventArgs 参数描述解析,并指示托管 StaticResource 引用的对象和属性及用于解析的  ResourceDictionary 和密钥: The StaticResourceResolvedEventArgs arguments describe the resolution, and indicate the object and property that host the StaticResource reference and the ResourceDictionary and key used for the resolution:

public class StaticResourceResolvedEventArgs : EventArgs
{
   public Object TargetObject { get; }

   public Object TargetProperty { get; }

   public ResourceDictionary ResourceDictionary { get; }

   public object ResourceKey { get; }
}
Public Class StaticResourceResolvedEventArgs : Inherits EventArgs
   Public ReadOnly Property TargetObject As Object
   Public ReadOnly Property TargetProperty As Object
   Public ReadOnly Property ResourceDictionary As ResourceDictionary
   Public ReadOnly Property ResourceKey As Object
End Class

除非启用  VisualDiagnostics 并设置了 ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO  环境变量,否则不会引发该事件(且忽略它的 add 访问器)。The event is not raised (and its add accessor is ignored) unless VisualDiagnostics is enabled and the ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO environment variable is set.

ClickOnceClickOnce

Windows 窗体的 HDPI 感知应用程序、Windows Presentation Foundation (WPF) 以及 Visual Studio Tools for Office (VSTO) 都可以通过使用 ClickOnce 进行部署。HDPI-aware applications for Windows Forms, Windows Presentation Foundation (WPF), and Visual Studio Tools for Office (VSTO) can all be deployed by using ClickOnce. 如果在应用程序清单中找到了以下条目,则部署将在 .NET Framework 4.7.2 下成功执行:If the following entry is found in the application manifest, deployment will succeed under .NET Framework 4.7.2:

<windowsSettings>
   <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>

对于 Windows 窗体应用程序,不需要像以前那样在应用程序配置文件(而非应用程序清单)中设置 DPI 感知就可以成功完成 ClickOnce 部署。For Windows Forms application, the previous workaround of setting DPI awareness in the application configuration file rather than the application manifest is no longer necessary for ClickOnce deployment to succeed.

.NET Framework 4.7.1 中的新增功能What's new in .NET Framework 4.7.1

.NET Framework 4.7.1 在以下几个领域新增了功能:.NET Framework 4.7.1 includes new features in the following areas:

此外,.NET Framework 4.7.1 的重点是改进了辅助功能,使应用程序能为使用辅助技术的用户提供最佳体验。In addition, a major focus in .NET Framework 4.7.1 is improved accessibility, which allows an application to provide an appropriate experience for users of Assistive Technology. 有关 .NET Framework 4.7.1 中辅助功能改进的信息,请参阅 .NET Framework 中辅助功能的新增功能For information on accessibility improvements in .NET Framework 4.7.1, see What's new in accessibility in the .NET Framework.

基类Base classes

支持 .NET Standard 2.0Support for .NET Standard 2.0

.NET Standard 定义一组 API,这些 API 必须可用于支持 Standard 版本的每个 .NET 实现。.NET Standard defines a set of APIs that must be available on each .NET implementation that supports that version of the standard. .NET Framework 4.7.1 完全支持 .NET Standard 2.0 并增加了 200 个 API,这些 API 在 .NET Standard 2.0 中定义,.NET Framework 4.6.1、4.6.2 和 4.7 中也延续使用。.NET Framework 4.7.1 fully supports .NET Standard 2.0 and adds about 200 APIs that are defined in .NET Standard 2.0 and are missing from .NET Framework 4.6.1, 4.6.2, and 4.7. (请注意,这些版本的 .NET Framework 只有在其他 .NET Standard 支持文件也部署在目标系统时才支持 .NET Standard 2.0。)有关详细信息,请参阅 .NET Framework 4.7.1 Runtime and Compiler Features(.NET Framework 4.7.1 运行时和编译器功能)博客文章中的“BCL - .NET Standard 2.0 Support”(BCL - .NET Standard 2.0 支持)。(Note that these versions of the .NET Framework support .NET Standard 2.0 only if additional .NET Standard support files are also deployed on the target system.) For more information, see "BCL - .NET Standard 2.0 Support" in the .NET Framework 4.7.1 Runtime and Compiler Features blog post.

支持配置生成器Support for configuration builders

配置生成器允许开发者在运行时动态地插入和生成应用程序的配置设置。Configuration builders allow developers to inject and build configuration settings for applications dynamically at run time. 自定义配置生成器可用于修改配置节中的现有数据,也可用于生成全新的配置节。Custom configuration builders can be used to modify existing data in a configuration section or to build a configuration section entirely from scratch. 如果没有配置生成器,.config 文件将是静态的,并且其设置将在应用程序启动之前定义。Without configuration builders, .config files are static, and their settings are defined some time before an application is launched.

若要创建自定义配置生成器,请从抽象的 ConfigurationBuilder 类派生生成器并且替代其 ConfigurationBuilder.ProcessConfigurationSectionConfigurationBuilder.ProcessRawXmlTo create a custom configuration builder, you derive your builder from the abstract ConfigurationBuilder class and override its ConfigurationBuilder.ProcessConfigurationSection and ConfigurationBuilder.ProcessRawXml. 也可在 .config 文件中定义生成器。You also define your builders in your .config file. 有关详细信息,请参阅 .NET Framework 4.7.1 ASP.NET and Configuration Features(.NET Framework 4.7.1 ASP.NET 和配置功能)博客文章中的“Configuration Builders”(配置生成器)一节。For more information, see the "Configuration Builders" section in the .NET Framework 4.7.1 ASP.NET and Configuration Features blog post.

运行时功能检测Run-time feature detection

System.Runtime.CompilerServices.RuntimeFeature 类提供一种机制,用于确定给定的 .NET 实现在编译时或运行时是否支持预定义的功能。The System.Runtime.CompilerServices.RuntimeFeature class provides a mechanism for determine whether a predefined feature is supported on a given .NET implementation at compile time or run time. 在编译时,编译器可以检查指定的字段是否存在,以确定是否支持某项功能,如果支持,它会发出利用这一功能的代码。At compile time, a compiler can check whether a specified field exists to determine whether the feature is supported; if so, it can emit code that takes advantage of that feature. 在运行时,应用程序可以在运行时发出代码之前调用 RuntimeFeature.IsSupported 方法。At run time, an application can call the RuntimeFeature.IsSupported method before emitting code at runtime. 有关详细信息,请参阅 Add helper method to describe features supported by the runtime(添加 helper 方法以描述运行时支持的功能)。For more information, see Add helper method to describe features supported by the runtime.

值元组类型是可序列化的Value tuple types are serializable

从 .NET Framework 4.7.1 起,System.ValueTuple 及其相关的泛型类型被标记为可序列化,允许进行二进制序列化。Starting with .NET Framework 4.7.1, System.ValueTuple and its associated generic types are marked as Serializable, which allows binary serialization. 这样,可以更轻松地将元组类型(如 Tuple<T1,T2,T3>Tuple<T1,T2,T3,T4>)迁移到值元组类型。This should make migrating Tuple types, such as Tuple<T1,T2,T3> and Tuple<T1,T2,T3,T4>, to value tuple types easier. 有关详细信息,请参阅 .NET Framework 4.7.1 Runtime and Compiler Features(.NET Framework 4.7.1 运行时和编译器功能)博客文章中的“Compiler -- ValueTuple is Serializable”(编译器 -- 值元组是可序列化的)。For more information, see "Compiler -- ValueTuple is Serializable" in the .NET Framework 4.7.1 Runtime and Compiler Features blog post.

支持只读引用Support for read-only references

.NET Framework 4.7.1 增加了 System.Runtime.CompilerServices.IsReadOnlyAttribute.NET Framework 4.7.1 adds the System.Runtime.CompilerServices.IsReadOnlyAttribute. 此特性由语言编译器用于标记具有只读 ref 返回类型或参数的成员。This attribute is used by language compilers to mark members that have read-only ref return types or parameters. 有关详细信息,请参阅 .NET Framework 4.7.1 Runtime and Compiler Features(.NET Framework 4.7.1 运行时和编译器功能)博客文章中的“Compiler -- Support for ReadOnlyReferences”(编译器 -- 支持只读引用)。For more information, see "Compiler -- Support for ReadOnlyReferences" in the .NET Framework 4.7.1 Runtime and Compiler Features blog post. 有关 ref 返回值的信息,请参阅 ref 返回值和 ref 局部变量(C# 指南)ref 返回值 (Visual Basic)For information on ref return values, see Ref return values and ref locals (C# Guide) and Ref return values (Visual Basic).

公共语言运行时 (CLR)Common language runtime (CLR)

垃圾回收性能改进Garbage collection performance improvements

.NET Framework 4.7.1 中的垃圾回收 (GC) 的更改提升了整体性能,尤其是大型对象堆 (LOH) 分配的性能。Changes to garbage collection (GC) in .NET Framework 4.7.1 improve overall performance, especially for large object heap (LOH) allocations. 在 .NET Framework 4.7.1 中,小型对象堆 (SOH) 分配和 LOH 分配使用不同的锁,当后台 GC 整理 SOH 时即发生 LOH 分配。In .NET Framework 4.7.1, separate locks are used for small object heap (SOH) and LOH allocations, which allows LOH allocations to occur when background GC is sweeping the SOH. 这样,进行大量 LOH 分配的应用程序发生分配锁争用的情况将减少,从而提高性能。As a result, applications that make a large number of LOH allocations should see a reduction in allocation lock contention and improved performance. 有关详细信息,请参阅 .NET Framework 4.7.1 Runtime and Compiler Features(.NET Framework 4.7.1 运行时和编译器功能)博客文章中的“Runtime -- GC Performance Improvements”(运行时 -- GC 性能改进)一节。For more information, see the "Runtime -- GC Performance Improvements" section in the .NET Framework 4.7.1 Runtime and Compiler Features blog post.

网络Networking

Message.HashAlgorithm 的 SHA-2 支持SHA-2 support for Message.HashAlgorithm

在 .NET Framework 4.7 及早期版本中,Message.HashAlgorithm 属性仅支持 HashAlgorithm.Md5HashAlgorithm.Sha 的值。In .NET Framework 4.7 and earlier versions, the Message.HashAlgorithm property supported values of HashAlgorithm.Md5 and HashAlgorithm.Sha only. 从 .NET Framework 4.7.1 开始,还支持 HashAlgorithm.Sha256HashAlgorithm.Sha384HashAlgorithm.Sha512Starting with .NET Framework 4.7.1, HashAlgorithm.Sha256, HashAlgorithm.Sha384, and HashAlgorithm.Sha512 are also supported. 实际是否使用此值取决于消息队列,因为 Message 实例本身不进行哈希处理,而是简单地将值传递到消息队列。Whether this value is actually used depends on MSMQ, since the Message instance itself does no hashing but simply passes on values to MSMQ. 有关详细信息,请参阅 .NET Framework 4.7.1 ASP.NET and Configuration Features(.NET Framework 4.7.1 ASP.NET 和配置功能)博客文章中的“SHA-2 support for Message.HashAlgorithm”(Message.HashAlgorithm 的 SHA-2 支持)一节。For more information, see the "SHA-2 support for Message.HashAlgorithm" section in the .NET Framework 4.7.1 ASP.NET and Configuration features blog post.

ASP.NETASP.NET

ASP.NET 应用程序中的执行步骤Execution steps in ASP.NET applications

ASP.NET 处理包括 23 个事件的预定义管道中的请求。ASP.NET processes requests in a predefined pipeline that includes 23 events. ASP.NET 执行每个事件处理程序作为一个执行步骤。ASP.NET executes each event handler as an execution step. 对于 .NET Framework 4.7 之前的 ASP.NET 版本,由于本机和托管线程之间的切换,ASP.NET 无法传送执行上下文。In versions of ASP.NET up to .NET Framework 4.7, ASP.NET can't flow the execution context due to switching between native and managed threads. ASP.NET 有选择性地仅传送 HttpContextInstead, ASP.NET selectively flows only the HttpContext. 从 .NET Framework 4.7.1 开始,HttpApplication.OnExecuteRequestStep(Action<HttpContextBase,Action>) 方法还允许模块还原环境数据。Starting with .NET Framework 4.7.1, the HttpApplication.OnExecuteRequestStep(Action<HttpContextBase,Action>) method also allows modules to restore ambient data. 此功能针对与跟踪、分析、诊断或事务(例如应用程序的执行流)相关的库。This feature is targeted at libraries concerned with tracing, profiling, diagnostics, or transactions, for example, that care about the execution flow of the application. 有关详细信息,请参阅 .NET Framework 4.7.1 ASP.NET and Configuration Features(.NET Framework 4.7.1 ASP.NET 和配置功能)博客文章的“ASP.NET Execution Step Feature”(ASP.NET 执行步骤功能)一节。For more information, see the "ASP.NET Execution Step Feature" in the .NET Framework 4.7.1 ASP.NET and Configuration Features blog post.

ASP.NET HttpCookie 分析ASP.NET HttpCookie parsing

.NET Framework 4.7.1 包括新的方法 HttpCookie.TryParse,此方法提供标准化的方式来从字符串创建 HttpCookie 对象,并精确分配 cookie 值(如过期日期和路径)。.NET Framework 4.7.1 includes a new method, HttpCookie.TryParse, that provides a standardized way to create an HttpCookie object from a string and accurately assign cookie values such as expiration date and path. 有关详细信息,请参阅 .NET Framework 4.7.1 ASP.NET and Configuration Features(.NET Framework 4.7.1 ASP.NET 和配置功能)博客文章中的“ASP.NET HttpCookie parsing”(ASP.NET HttpCookie 分析)一节。For more information, see "ASP.NET HttpCookie parsing" in the .NET Framework 4.7.1 ASP.NET and Configuration Features blog post.

ASP.NET 窗体身份验证凭据的 SHA-2 哈希选项SHA-2 hash options for ASP.NET forms authentication credentials

在 .NET Framework 4.7 及其早期版本中,ASP.NET 允许开发者使用 MD5 或 SHA1 在配置文件中存储用户凭据和哈希密码。In .NET Framework 4.7 and earlier versions, ASP.NET allowed developers to store user credentials with hashed passwords in configuration files using either MD5 or SHA1. 从 .NET Framework 4.7.1 开始,ASP.NET 还支持新的安全 SHA-2 哈希选项(如 SHA256、SHA384 和 SHA512)。Starting with .NET Framework 4.7.1, ASP.NET also supports new secure SHA-2 hash options such as SHA256, SHA384, and SHA512. SHA1 保留默认值,非默认哈希算法可以在 Web 配置文件中定义。SHA1 remains the default, and a non-default hash algorithm can be defined in the web configuration file. 例如:For example:

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="~/login.aspx">
          <credentials passwordFormat="SHA512">
            <user name="jdoe" password="6D003E98EA1C7F04ABF8FCB375388907B7F3EE06F278DB966BE960E7CBBD103DF30CA6D61F7E7FD981B2E4E3A64D43C836A4BEDCA165C33B163E6BCDC538A664" />
          </credentials>
        </forms>
    </authentication>
</system.web>

.NET Framework 4.7 中的新增功能What's new in .NET Framework 4.7

.NET Framework 4.7 在以下几个领域新增了功能:.NET Framework 4.7 includes new features in the following areas:

有关 .NET Framework 4.7 中新增 API 的列表,请参阅 GitHub 上的 .NET Framework 4.7 API 更改For a list of new APIs added to .NET Framework 4.7, see .NET Framework 4.7 API Changes on GitHub. 有关 .NET Framework 4.7 中功能改进和 bug 修复的列表,请参阅 GitHub 上的 .NET Framework 4.7 更改列表For a list of feature improvements and bug fixes in .NET Framework 4.7, see .NET Framework 4.7 List of Changes on GitHub. 有关其他信息,请参阅 .NET 博客中的 Announcing the .NET Framework 4.7(宣布 .NET Framework 4.7)。For additional information, see Announcing the .NET Framework 4.7 in the .NET blog.

基类Base classes

.NET Framework 4.7 通过 DataContractJsonSerializer 改进了序列化:.NET Framework 4.7 improves serialization by the DataContractJsonSerializer:

借助椭圆曲线加密 (ECC) 增强了功能*Enhanced functionality with Elliptic Curve Cryptography (ECC)*

在 .NET Framework 4.7 中,ImportParameters(ECParameters) 方法已添加到 ECDsaECDiffieHellman 类,以允许对象表示已经建立的密钥。In .NET Framework 4.7, ImportParameters(ECParameters) methods were added to the ECDsa and ECDiffieHellman classes to allow for an object to represent an already-established key. 此外,还添加了 ExportParameters(Boolean) 方法,以便于使用显式曲线参数导出密钥。An ExportParameters(Boolean) method was also added for exporting the key using explicit curve parameters.

.NET Framework 4.7 现已开始支持其他曲线(其中包括 Brainpool 曲线套件),并添加了预定义的定义,以便于通过新工厂方法 CreateCreate 简化创建操作。.NET Framework 4.7 also adds support for additional curves (including the Brainpool curve suite), and has added predefined definitions for ease-of-creation through the new Create and Create factory methods.

有关 .NET Framework 4.7 加密改进示例,请访问 GitHub。You can see an example of .NET Framework 4.7 cryptography improvements on GitHub.

通过 DataContractJsonSerializer 提供更出色的控制字符支持Better support for control characters by the DataContractJsonSerializer

在 .NET Framework 4.7 中,DataContractJsonSerializer 串行化符合 ECMAScript 6 标准的控制字符。In .NET Framework 4.7, the DataContractJsonSerializer serializes control characters in conformity with the ECMAScript 6 standard. 定位 .NET Framework 4.7 的应用程序默认启用此行为,而对于在 .NET Framework 4.7 控制下运行,但定位的是旧版 .NET Framework 的应用程序来说,这就是一项选择启用功能。This behavior is enabled by default for applications that target .NET Framework 4.7, and is an opt-in feature for applications that are running under .NET Framework 4.7 but target a previous version of the .NET Framework. 有关详细信息,请参阅 .NET Framework 4.7 中的重定目标更改For more information, see Retargeting Changes in the .NET Framework 4.7.

网络Networking

.NET Framework 4.7 新增了以下网络相关功能:.NET Framework 4.7 adds the following network-related feature:

提供对 TLS 协议的默认操作系统支持*Default operating system support for TLS protocols*

借助 System.Net.Security.SslStream 和上托堆栈组件(如 HTTP、FTP 和 SMTP)使用的 TLS 堆栈,开发者可以使用操作系统支持的默认 TLS 协议。The TLS stack, which is used by System.Net.Security.SslStream and up-stack components such as HTTP, FTP, and SMTP, allows developers to use the default TLS protocols supported by the operating system. 开发者再也不需要对 TLS 版本进行硬编码。Developers need no longer hard-code a TLS version.

ASP.NETASP.NET

在 .NET Framework 4.7 中,ASP.NET 新增了以下功能:In .NET Framework 4.7, ASP.NET includes the following new features:

对象缓存扩展性Object Cache Extensibility

自 .NET Framework 4.7 起,ASP.NET 新增了一组 API,以便开发者可以替换内存中对象缓存和内存监视的默认 ASP.NET 实现代码。Starting with .NET Framework 4.7, ASP.NET adds a new set of APIs that allow developers to replace the default ASP.NET implementations for in-memory object caching and memory monitoring. 现在,如果 ASP.NET 实现代码不充分,开发者可以替换以下三个组件中的任意一个:Developers can now replace any of the following three components if the ASP.NET implementation is not adequate:

  • 对象缓存存储Object Cache Store. 在新的缓存提供程序配置部分中,开发者可以使用新接口 ICacheStoreProvider 为 ASP.NET 应用程序插入对象缓存的新实现代码。By using the new cache providers configuration section, developers can plug in new implementations of an object cache for an ASP.NET application by using the new ICacheStoreProvider interface.

  • 内存监视Memory monitoring. 当运行的应用程序接近所配置的专用字节进程限制,或计算机的可用总物理内存不足时,ASP.NET 中的默认内存监视器就会通知应用程序。The default memory monitor in ASP.NET notifies applications when they are running close to the configured private bytes limit for the process, or when the machine is low on total available physical RAM. 接近这些限制时,就会触发通知。When these limits are near, notifications are fired. 对于某些应用程序,通知的触发点与限制过近,无法及时响应。For some applications, notifications are fired too close to the configured limits to allow for useful reactions. 开发人员现在可以编写自己的内存监视器,以通过使用 ApplicationMonitors.MemoryMonitor 属性替换默认的内存监视器。Developers can now write their own memory monitors to replace the default by using the ApplicationMonitors.MemoryMonitor property.

  • 内存限制响应Memory Limit Reactions. 默认情况下,当接近专用字节进程限制时,ASP.NET 会尝试释放对象缓存,并定期调用 GC.CollectBy default, ASP.NET attempts to trim the object cache and periodically call GC.Collect when the private byte process limit is near. 对于某些应用程序,GC.Collect 调用频率或缓存释放量的效率低下。For some applications, the frequency of calls to GC.Collect or the amount of cache that is trimmed are inefficient. 开发者现在可以向应用程序的内存监视器添加 IObserver 实现代码,从而替换或补充默认行为。Developers can now replace or supplement the default behavior by subscribing IObserver implementations to the application's memory monitor.

Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) 新增了以下功能和更改:Windows Communication Foundation (WCF) adds the following features and changes:

能够配置 TLS 1.1 或 TLS 1.2 默认消息安全设置Ability to configure the default message security settings to TLS 1.1 or TLS 1.2

自 .NET Framework 4.7 起,除了 SSL 3.0 和 TLS 1.0 外,WCF 还允许配置 TLS 1.1 或 TLS 1.2 作为默认消息安全协议。Starting with .NET Framework 4.7, WCF allows you to configure TSL 1.1 or TLS 1.2 in addition to SSL 3.0 and TSL 1.0 as the default message security protocol. 这是一项选择启用设置;必须向应用程序配置文件添加以下条目,才能启用此设置:This is an opt-in setting; to enable it, you must add the following entry to your application configuration file:

<runtime>
   <AppContextSwitchOverrides value="Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols=false;Switch.System.Net.DontEnableSchUseStrongCrypto=false" />
</runtime>

提升了 WCF 应用程序和 WCF 序列化的可靠性Improved reliability of WCF applications and WCF serialization

WCF 包含大量代码更改,消除了争用条件,从而提升了序列化选项的性能和可靠性。WCF includes a number of code changes that eliminate race conditions, thereby improving performance and the reliability of serialization options. 其中包括:These include:

  • 更好地支持在调用 SocketConnection.BeginReadSocketConnection.Read 时混合异步和同步代码。Better support for mixing asynchronous and synchronous code in calls to SocketConnection.BeginRead and SocketConnection.Read.
  • 提升了在中止与 SharedConnectionListenerDuplexChannelBinder 的连接时的可靠性。Improved reliability when aborting a connection with SharedConnectionListener and DuplexChannelBinder.
  • 提高了调用 FormatterServices.GetSerializableMembers(Type) 方法时序列化操作的可靠性。Improved reliability of serialization operations when calling the FormatterServices.GetSerializableMembers(Type) method.
  • 提升了在调用 ChannelSynchronizer.RemoveWaiter 方法以删除等待程序时的可靠性。Improved reliability when removing a waiter by calling the ChannelSynchronizer.RemoveWaiter method.

Windows 窗体Windows Forms

在 .NET Framework 4.7 中,Windows 窗体改进了对高 DPI 监视器的支持。In .NET Framework 4.7, Windows Forms improves support for high DPI monitors.

高 DPI 支持High DPI support

自定位 .NET Framework 4.7 的应用程序起,.NET Framework 为 Windows 窗体应用程序提供高 DPI 和动态 DPI 支持。Starting with applications that target .NET Framework 4.7, the .NET Framework features high DPI and dynamic DPI support for Windows Forms applications. 高 DPI 支持改进了高 DPI 监视器上窗体和控件的布局和外观。High DPI support improves the layout and appearance of forms and controls on high DPI monitors. 当用户更改正在运行的应用程序的 DPI 或显示比例系数时,动态 DPI 会更改窗体和控件的布局和外观。Dynamic DPI changes the layout and appearance of forms and controls when the user changes the DPI or display scale factor of a running application.

高 DPI 支持是一项选择启用功能,配置方法为在应用程序配置文件中定义 <System.Windows.Forms.ConfigurationSection> 部分。High DPI support is an opt-in feature that you configure by defining a <System.Windows.Forms.ConfigurationSection> section in your application configuration file. 若要详细了解如何向 Windows 窗体应用程序添加高 DPI 支持和动态 DPI 支持,请参阅 Windows 窗体中的高 DPI 支持For more information on adding high DPI support and dynamic DPI support to your Windows Forms application, see High DPI Support in Windows Forms.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

在 .NET Framework 4.7 中,WPF 新增了以下增强功能:In .NET Framework 4.7, WPF includes the following enhancements:

支持基于 Windows WM_POINTER 消息的触控/触笔堆栈Support for a touch/stylus stack based on Windows WM_POINTER messages

现在可以视情况使用基于 WM_POINTER 消息的触控/触笔堆栈,而不使用 Windows Ink 服务平台 (WISP)。You now have the option of using a touch/stylus stack based on WM_POINTER messages instead of the Windows Ink Services Platform (WISP). 这是 .NET Framework 中的一项选择启用功能。This is an opt-in feature in the .NET Framework. 有关详细信息,请参阅 .NET Framework 4.7 中的重定目标更改For more information, see Retargeting Changes in the .NET Framework 4.7.

WPF 打印 API 的新实现代码New implementation for WPF printing APIs

System.Printing.PrintQueue 类中的 WPF 打印 API 调用 Windows 打印文档包 API,而不调用弃用的 XPS 打印 APIWPF's printing APIs in the System.Printing.PrintQueue class call the Windows Print Document Package API instead of the deprecated XPS Print API. 若要了解此更改对应用程序兼容性造成的影响,请参阅 .NET Framework 4.7 中的重定目标更改For the impact of this change on application compatibility, see Retargeting Changes in the .NET Framework 4.7.

.NET Framework 4.6.2 中的新增功能What's new in .NET Framework 4.6.2

.NET Framework 4.6.2 在以下几个领域新增了功能:The .NET Framework 4.6.2 includes new features in the following areas:

有关 .NET Framework 4.6.2 中新增 API 的列表,请参阅 GitHub 上的 .NET Framework 4.6.2 API 更改For a list of new APIs added to .NET Framework 4.6.2, see .NET Framework 4.6.2 API Changes on GitHub. 有关 .NET Framework 4.6.2 中功能改进和 bug 修复的列表,请参阅 GitHub 上的 .NET Framework 4.6.2 更改列表For a list of feature improvements and bug fixes in .NET Framework 4.6.2, see .NET Framework 4.6.2 List of Changes on GitHub. 有关其他信息,请参阅 .NET 博客中的 Announcing .NET Framework 4.6.2(宣布 .NET Framework 4.6.2)。For additional information, see Announcing .NET Framework 4.6.2 in the .NET blog.

ASP.NETASP.NET

在 .NET Framework 4.6.2 中,ASP.NET 包括以下增强功能:In the .NET Framework 4.6.2, ASP.NET includes the following enhancements:

改进了对数据注释验证程序中本地化错误消息的支持Improved support for localized error messages in data annotation validators

数据批注验证程序使你能够通过将一个或多个属性添加到类属性来执行验证。Data annotation validators enable you to perform validation by adding one or more attributes to a class property. 如果验证失败,该属性的 ValidationAttribute.ErrorMessage 元素定义错误消息的文本。The attribute's ValidationAttribute.ErrorMessage element defines the text of the error message if validation fails. 自 .NET Framework 4.6.2 起,ASP.NET 简化了错误消息的本地化。Starting with the .NET Framework 4.6.2, ASP.NET makes it easy to localize error messages. 如果有以下情况,将本地化错误消息:Error messages will be localized if:

  1. 验证属性中提供 ValidationAttribute.ErrorMessageThe ValidationAttribute.ErrorMessage is provided in the validation attribute.

  2. 资源文件存储在 App_LocalResources 文件夹中。The resource file is stored in the App_LocalResources folder.

  3. 本地化资源文件名称的格式为 DataAnnotation.Localization.{name}.resx,其中 name 是采用 languageCode-country/regionCodelanguageCode 格式的区域性名称。The name of the localized resources file has the form DataAnnotation.Localization.{name}.resx, where name is a culture name in the format languageCode-country/regionCode or languageCode.

  4. 该资源的项名称是分配给 ValidationAttribute.ErrorMessage 属性的字符串,其值是本地化的错误消息。The key name of the resource is the string assigned to the ValidationAttribute.ErrorMessage attribute, and its value is the localized error message.

例如,以下数据注释属性定义无效分级的默认区域性错误消息。For example, the following data annotation attribute defines the default culture's error message for an invalid rating.

public class RatingInfo
{
   [Required(ErrorMessage = "The rating must be between 1 and 10.")]
   [Display(Name = "Your Rating")]
   public int Rating { get; set; }
}
Public Class RatingInfo
   <Required(ErrorMessage = "The rating must be between 1 and 10.")>
   <Display(Name = "Your Rating")>
   Public Property Rating As Integer = 1
End Class

然后可以创建一个资源文件 DataAnnotation.Localization.fr.resx,它的键为错误消息字符串,值为本地化的错误消息。You can then create a resource file, DataAnnotation.Localization.fr.resx, whose key is the error message string and whose value is the localized error message. 该文件必须位于 App.LocalResources 文件夹中。The file must be found in the App.LocalResources folder. 例如,下面列出了键以及它在本地化法语 (fr) 错误消息中的值:For example, the following is the key and its value in a localized French (fr) language error message:

nameName Value
分级必须介于 1 和 10 之间。The rating must be between 1 and 10. La note doit être comprise entre 1 et 10.La note doit être comprise entre 1 et 10.

此外,数据批注本地化可扩展。In addition, data annotation localization is extensible. 开发人员可以通过实现 IStringLocalizerProvider 接口插入自己的字符串本地化工具提供程序,以将本地化字符串存储在资源文件以外的某个位置。Developers can plug in their own string localizer provider by implementing the IStringLocalizerProvider interface to store localization string somewhere other than in a resource file.

会话状态存储提供程序的异步支持Async support with session-state store providers

ASP.NET 现允许将返回任务的方法与会话状态存储提供程序一起使用,从而允许 ASP.NET 应用获取异步的可伸缩性优势。ASP.NET now allows task-returning methods to be used with session-state store providers, thereby allowing ASP.NET apps to get the scalability benefits of async. 要使用会话状态存储提供程序支持异步操作,ASP.NET 包括一个新的接口 System.Web.SessionState.ISessionStateModule,它继承自 IHttpModule 并允许开发人员实现其自己的会话状态模块和异步会话存储提供程序。To supports asynchronous operations with session state store providers, ASP.NET includes a new interface, System.Web.SessionState.ISessionStateModule, which inherits from IHttpModule and allows developers to implement their own session-state module and async session store providers. 接口定义如下:The interface is defined as follows:

public interface ISessionStateModule : IHttpModule {
    void ReleaseSessionState(HttpContext context);
    Task ReleaseSessionStateAsync(HttpContext context);
}
Public Interface ISessionStateModule : Inherits IHttpModule
   Sub ReleaseSessionState(context As HttpContext)
   Function ReleaseSessionStateAsync(context As HttpContext) As Task
End Interface

此外,SessionStateUtility 类包括两种新方法:IsSessionStateReadOnlyIsSessionStateRequired,可用来支持异步操作。In addition, the SessionStateUtility class includes two new methods, IsSessionStateReadOnly and IsSessionStateRequired, that can be used to support asynchronous operations.

对输出缓存提供程序的异步支持Async support for output-cache providers

自 .NET Framework 4.6.2 起,返回任务的方法可与输出缓存提供程序结合使用,从而实现异步的可伸缩性优势。Starting with the .NET Framework 4.6.2, task-returning methods can be used with output-cache providers to provide the scalability benefits of async. 实现这些方法的提供程序减少了 Web 服务器上的线程阻止,并提高 ASP.NET 服务的可伸缩性。Providers that implement these methods reduce thread-blocking on a web server and improve the scalability of an ASP.NET service.

添加了以下 API 以支持异步输出缓存提供程序:The following APIs have been added to support asynchronous output-cache providers:

字符类别Character categories

.NET Framework 4.6.2 中的字符是根据 Unicode 标准 8.0.0 版进行分类的。Characters in the .NET Framework 4.6.2 are classified based on the Unicode Standard, Version 8.0.0. 在 .NET Framework 4.6 和 .NET Framework 4.6.1 中,字符是根据 Unicode 6.3 字符类别进行分类。In .NET Framework 4.6 and .NET Framework 4.6.1, characters were classified based on Unicode 6.3 character categories.

对 Unicode 8.0 的支持限于 CharUnicodeInfo 类的字符分类以及依赖它的类型和方法。Support for Unicode 8.0 is limited to the classification of characters by the CharUnicodeInfo class and to types and methods that rely on it. 其中包括 StringInfo 类、重载的 Char.GetUnicodeCategory 方法和 .NET Framework 正则表达式引擎识别的字符类These include the StringInfo class, the overloaded Char.GetUnicodeCategory method, and the character classes recognized by the .NET Framework regular expression engine. 字符及字符串的比较和排序不受此更改影响,仍依赖于基础操作系统,或 Windows 7 系统、.NET Framework 提供的字符数据。Character and string comparison and sorting is unaffected by this change and continues to rely on the underlying operating system or, on Windows 7 systems, on character data provided by the .NET Framework.

有关从 Unicode 6.0 到 Unicode 7.0 的字符类别的更改,请参阅 Unicode Consortium 网站上的 Unicode 标准 7.0.0 版For changes in character categories from Unicode 6.0 to Unicode 7.0, see The Unicode Standard, Version 7.0.0 at The Unicode Consortium website. 有关从 Unicode 7.0 到 Unicode 8.0 的更改,请参阅 Unicode Consortium 网站上的 Unicode 标准 8.0.0 版For changes from Unicode 7.0 to Unicode 8.0, see The Unicode Standard, Version 8.0.0 at The Unicode Consortium website.

密码Cryptography

对包含 FIPS 186-3 DSA 的 X509 证书的支持Support for X509 certificates containing FIPS 186-3 DSA

.NET Framework 4.6.2 现已开始支持密钥超过 FIPS 186-2 1024 位限制的 DSA(数字签名算法)X509 证书。The .NET Framework 4.6.2 adds support for DSA (Digital Signature Algorithm) X509 certificates whose keys exceed the FIPS 186-2 1024-bit limit.

除了支持更大的 FIPS 186-3 密钥大小之外,.NET Framework 4.6.2 还支持使用 SHA-2 系列的哈希算法(SHA256、SHA384 和 SHA512)计算签名。In addition to supporting the larger key sizes of FIPS 186-3, the .NET Framework 4.6.2 allows computing signatures with the SHA-2 family of hash algorithms (SHA256, SHA384, and SHA512). FIPS 186-3 支持由新的 System.Security.Cryptography.DSACng 类提供。FIPS 186-3 support is provided by the new System.Security.Cryptography.DSACng class.

为了跟进 .NET Framework 4.6 中的 RSA 类和 .NET Framework 4.6.1 中的 ECDsa 类的最新更改,.NET Framework 4.6.2 中的 DSA 抽象基类有附加方法允许调用方在无需强制转换即可使用此功能。In keeping with recent changes to the RSA class in .NET Framework 4.6 and the ECDsa class in .NET Framework 4.6.1, the DSA abstract base class in .NET Framework 4.6.2 has additional methods to allow callers to use this functionality without casting. 可以调用 DSACertificateExtensions.GetDSAPrivateKey 扩展方法对数据进行签名,如以下示例所示。You can call the DSACertificateExtensions.GetDSAPrivateKey extension method to sign data, as the following example shows.

public static byte[] SignDataDsaSha384(byte[] data, X509Certificate2 cert)
{
    using (DSA dsa = cert.GetDSAPrivateKey())
    {
        return dsa.SignData(data, HashAlgorithmName.SHA384);
    }
}
Public Shared Function SignDataDsaSha384(data As Byte(), cert As X509Certificate2) As Byte()
    Using DSA As DSA = cert.GetDSAPrivateKey()
        Return DSA.SignData(data, HashAlgorithmName.SHA384)
    End Using
End Function

并且可以调用 DSACertificateExtensions.GetDSAPublicKey 扩展方法验证已签名的数据,如以下示例所示。And you can call the DSACertificateExtensions.GetDSAPublicKey extension method to verify signed data, as the following example shows.

public static bool VerifyDataDsaSha384(byte[] data, byte[] signature, X509Certificate2 cert)
{
    using (DSA dsa = cert.GetDSAPublicKey())
    {
        return dsa.VerifyData(data, signature, HashAlgorithmName.SHA384);
    }
}
 Public Shared Function VerifyDataDsaSha384(data As Byte(), signature As Byte(), cert As X509Certificate2) As Boolean
    Using dsa As DSA = cert.GetDSAPublicKey()
        Return dsa.VerifyData(data, signature, HashAlgorithmName.SHA384)
    End Using
End Function

提高了 ECDiffieHellman 密钥派生例程的输入的清晰度Increased clarity for inputs to ECDiffieHellman key derivation routines

.NET Framework 3.5 通过三个不同的密钥派生功能 (KDF) 例程增加了对椭圆曲线 Diffie-Hellman 密钥协议的支持。.NET Framework 3.5 added support for Elliptic Curve Diffie-Hellman Key Agreement with three different Key Derivation Function (KDF) routines. 例程的输入以及这些例程本身通过 ECDiffieHellmanCng 对象上的属性进行配置。The inputs to the routines, and the routines themselves, were configured via properties on the ECDiffieHellmanCng object. 但由于不是每个例程都会读取每个输入属性,因此过去很有可能对开发人员造成了困扰。But since not every routine read every input property, there was ample room for confusion on the past of the developer.

为了在 .NET Framework 4.6.2 中解决这一问题,已向 ECDiffieHellman 基类添加以下三种方法,以便更明确地表示这些 KDF 例程及其输入:To address this in the .NET Framework 4.6.2, the following three methods have been added to the ECDiffieHellman base class to more clearly represent these KDF routines and their inputs:

ECDiffieHellman 方法ECDiffieHellman method 说明Description
DeriveKeyFromHash(ECDiffieHellmanPublicKey, HashAlgorithmName, Byte[], Byte[]) 使用下面的公式派生密钥材料Derives key material using the formula

HASH(secretPrepend || x || secretAppend)HASH(secretPrepend || x || secretAppend)

HASH(secretPrepend OrElse x OrElse secretAppend)HASH(secretPrepend OrElse x OrElse secretAppend)

其中 x 是 EC Diffie-Hellman 算法的计算结果。where x is the computed result of the EC Diffie-Hellman algorithm.
DeriveKeyFromHmac(ECDiffieHellmanPublicKey, HashAlgorithmName, Byte[], Byte[], Byte[]) 使用下面的公式派生密钥材料Derives key material using the formula

HMAC(hmacKey, secretPrepend || x || secretAppend)HMAC(hmacKey, secretPrepend || x || secretAppend)

HMAC(hmacKey, secretPrepend OrElse x OrElse secretAppend)HMAC(hmacKey, secretPrepend OrElse x OrElse secretAppend)

其中 x 是 EC Diffie-Hellman 算法的计算结果。where x is the computed result of the EC Diffie-Hellman algorithm.
DeriveKeyTls(ECDiffieHellmanPublicKey, Byte[], Byte[]) 使用 TLS 伪随机函数 (PRF) 派生算法派生密钥材料。Derives key material using the TLS pseudo-random function (PRF) derivation algorithm.

对持久化密钥对称加密的支持Support for persisted-key symmetric encryption

Windows 加密库 (CNG) 现已开始支持存储持久化对称密钥和使用硬件存储的对称密钥。开发者可通过 .NET Framework 4.6.2 使用此功能。The Windows cryptography library (CNG) added support for storing persisted symmetric keys and using hardware-stored symmetric keys, and the .NET Framework 4.6.2 made it possible for developers to make use of this feature. 因为密钥名和密钥提供程序的概念是特定于实现的,所以使用此功能要求使用具体实现类型(而不是首选出厂方法)的构造函数(例如,调用 Aes.Create)。Since the notion of key names and key providers is implementation-specific, using this feature requires utilizing the constructor of the concrete implementation types instead of the preferred factory approach (such as calling Aes.Create).

持久化密钥对称加密支持因 AES (AesCng) 和 3DES (TripleDESCng) 算法存在。Persisted-key symmetric encryption support exists for the AES (AesCng) and 3DES (TripleDESCng) algorithms. 例如:For example:

public static byte[] EncryptDataWithPersistedKey(byte[] data, byte[] iv)
{
    using (Aes aes = new AesCng("AesDemoKey", CngProvider.MicrosoftSoftwareKeyStorageProvider))
    {
        aes.IV = iv;

        // Using the zero-argument overload is required to make use of the persisted key
        using (ICryptoTransform encryptor = aes.CreateEncryptor())
        {
            if (!encryptor.CanTransformMultipleBlocks)
            {
                throw new InvalidOperationException("This is a sample, this case wasn’t handled...");
            }

            return encryptor.TransformFinalBlock(data, 0, data.Length);
        }
    }
}
Public Shared Function EncryptDataWithPersistedKey(data As Byte(), iv As Byte()) As Byte()
    Using Aes As Aes = New AesCng("AesDemoKey", CngProvider.MicrosoftSoftwareKeyStorageProvider)
        Aes.IV = iv

        ' Using the zero-argument overload Is required to make use of the persisted key
        Using encryptor As ICryptoTransform = Aes.CreateEncryptor()
            If Not encryptor.CanTransformMultipleBlocks Then
                Throw New InvalidOperationException("This is a sample, this case wasn’t handled...")
            End If
            Return encryptor.TransformFinalBlock(data, 0, data.Length)
        End Using
    End Using
End Function

对 SHA-2 哈希的 SignedXml 支持SignedXml support for SHA-2 hashing

.NET Framework 4.6.2 中的 SignedXml 类现已开始支持 RSA-SHA256、RSA-SHA384 和 RSA-SHA512 PKCS#1 签名方法,还支持 SHA256、SHA384 和 SHA512 引用摘要算法。The .NET Framework 4.6.2 adds support to the SignedXml class for RSA-SHA256, RSA-SHA384, and RSA-SHA512 PKCS#1 signature methods, and SHA256, SHA384, and SHA512 reference digest algorithms.

URI 常量都在 SignedXml 上公开:The URI constants are all exposed on SignedXml:

SignedXml 字段SignedXml field 返回的常量Constant
XmlDsigSHA256Url “http://www.w3.org/2001/04/xmlenc#sha256”"http://www.w3.org/2001/04/xmlenc#sha256"
XmlDsigRSASHA256Url “http://www.w3.org/2001/04/xmldsig-more#rsa-sha256”"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
XmlDsigSHA384Url “http://www.w3.org/2001/04/xmldsig-more#sha384”"http://www.w3.org/2001/04/xmldsig-more#sha384"
XmlDsigRSASHA384Url “http://www.w3.org/2001/04/xmldsig-more#rsa-sha384”"http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
XmlDsigSHA512Url “http://www.w3.org/2001/04/xmlenc#sha512”"http://www.w3.org/2001/04/xmlenc#sha512"
XmlDsigRSASHA512Url “http://www.w3.org/2001/04/xmldsig-more#rsa-sha512”"http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"

已将自定义 SignatureDescription 处理程序注册到 CryptoConfig 以添加对这些算法的支持的任何程序将会继续像过去一样工作,但由于现在有平台默认值,所以不再需要 CryptoConfig 注册。Any programs that have registered a custom SignatureDescription handler into CryptoConfig to add support for these algorithms will continue to function as they did in the past, but since there are now platform defaults, the CryptoConfig registration is no longer necessary.

SqlClientSqlClient

SQL Server 的 .NET framework 数据提供程序 (System.Data.SqlClient) 包括 .NET Framework 4.6.2 中的以下新功能:.NET Framework Data Provider for SQL Server (System.Data.SqlClient) includes the following new features in the .NET Framework 4.6.2:

Azure SQL 数据库的连接池和超时Connection pooling and timeouts with Azure SQL databases

启用连接池并出现超时或其他登录错误后,会缓存一个异常,并会在接下来的 5 秒到 1 分钟内尝试任何后续连接时引发缓存的异常。When connection pooling is enabled and a timeout or other login error occurs, an exception is cached, and the cached exception is thrown on any subsequent connection attempt for the next 5 seconds to 1 minute. 有关更多详细信息,请参阅 SQL Server 连接池 (ADO.NET)For more details, see SQL Server Connection Pooling (ADO.NET).

连接到 Azure SQL 数据库时此行为是不可取的,因为连接尝试可能会失败,出现通常会快速恢复的暂时性错误。This behavior is not desirable when connecting to Azure SQL Databases, since connection attempts can fail with transient errors that are typically recovered quickly. 为更好地优化连接重试体验,会在与 Azure SQL 数据库连接失败时删除连接池阻塞期行为。To better optimize the connection retry experience, the connection pool blocking period behavior is removed when connections to Azure SQL Databases fail.

PoolBlockingPeriod 关键字的添加使你能够选择最适合你的应用的阻塞期。The addition of the new PoolBlockingPeriod keyword lets you to select the blocking period best suited for your app. 值包括:Values include:

Auto

已禁用连接到 Azure SQL 数据库的应用程序的连接池阻塞期,已启用连接到任何其他 SQL Server 实例的应用程序的连接池阻塞期。The connection pool blocking period for an application that connects to an Azure SQL Database is disabled, and the connection pool blocking period for an application that connects to any other SQL Server instance is enabled. 这是默认值。This is the default value. 如果 Server 终结点名称采用以下任一结尾,则将它们视为 Azure SQL 数据库:If the Server endpoint name ends with any of the following, they are considered Azure SQL Databases:

  • .database.windows.net.database.windows.net

  • .database.chinacloudapi.cn.database.chinacloudapi.cn

  • .database.usgovcloudapi.net.database.usgovcloudapi.net

  • .database.cloudapi.de.database.cloudapi.de

AlwaysBlock

连接池阻塞期始终处于启用状态。The connection pool blocking period is always enabled.

NeverBlock

连接池阻塞期始终处于禁用状态。The connection pool blocking period is always disabled.

Always Encrypted 的增强功能Enhancements for Always Encrypted

SQLClient 引入了针对 Always Encrypted 的两个增强功能:SQLClient introduces two enhancements for Always Encrypted:

  • 为改善针对加密数据库列的参数化查询的性能,现会缓存查询参数的加密元数据。To improve performance of parameterized queries against encrypted database columns, encryption metadata for query parameters is now cached. SqlConnection.ColumnEncryptionQueryMetadataCacheEnabled 属性设置为 true(这是默认值)时,如果多次调用相同的查询,则客户端只从服务器检索一次参数元数据。With the SqlConnection.ColumnEncryptionQueryMetadataCacheEnabled property set to true (which is the default value), if the same query is called multiple times, the client retrieves parameter metadata from the server only once.

  • 密钥缓存中的列加密密钥条目现会在可配置时间间隔后被逐出,使用 SqlConnection.ColumnEncryptionKeyCacheTtl 属性设置。Column encryption key entries in the key cache are now evicted after a configurable time interval, set using the SqlConnection.ColumnEncryptionKeyCacheTtl property.

Windows Communication FoundationWindows Communication Foundation

在 .NET Framework 4.6.2 中,Windows Communication Foundation 在以下几个方面进行了增强:In the .NET Framework 4.6.2, Windows Communication Foundation has been enhanced in the following areas:

使用 CNG 对存储的证书的 WCF 传输安全支持WCF transport security support for certificates stored using CNG

WCF 传输安全使用 Windows 加密库 (CNG) 支持存储的证书。WCF transport security supports certificates stored using the Windows cryptography library (CNG). 在 .NET Framework 4.6.2 中,此支持仅限于将证书与指数长度不超过 32 位的公钥结合使用。In the .NET Framework 4.6.2, this support is limited to using certificates with a public key that has an exponent no more than 32 bits in length. 对于定位 .NET Framework 4.6.2 的应用程序,此功能默认启用。When an application targets the .NET Framework 4.6.2, this feature is on by default.

对面向 .NET Framework 4.6.1 及更低版本,但在 .NET Framework 4.6.2 上运行的应用程序,可在 app.config 或 web.config 文件的 <runtime> 部分中添加以下代码行来启用此功能。For applications that target the .NET Framework 4.6.1 and earlier but are running on the .NET Framework 4.6.2, this feature can be enabled by adding the following line to the <runtime> section of the app.config or web.config file.

<AppContextSwitchOverrides
    value="Switch.System.ServiceModel.DisableCngCertificates=false"
/>

这还可以使用代码以编程方式完成,如下所示:This can also be done programmatically with code like the following:

private const string DisableCngCertificates = @"Switch.System.ServiceModel.DisableCngCertificates";
AppContext.SetSwitch(disableCngCertificates, false);
Const DisableCngCertificates As String = "Switch.System.ServiceModel.DisableCngCertificates"
AppContext.SetSwitch(disableCngCertificates, False)

通过 DataContractJsonSerializer 类更好地支持多个夏令时调整规则Better support for multiple daylight saving time adjustment rules by the DataContractJsonSerializer class

客户可以使用应用程序配置设置来确定 DataContractJsonSerializer 类是否支持一个时区的多个调整规则。Customers can use an application configuration setting to determine whether the DataContractJsonSerializer class supports multiple adjustment rules for a single time zone. 这是一项可以选择使用的功能。This is an opt-in feature. 若要启用它,将以下设置添加到 app.config 文件中:To enable it, add the following setting to your app.config file:

<runtime>
     <AppContextSwitchOverrides value="Switch.System.Runtime.Serialization.DoNotUseTimeZoneInfo=false" />
</runtime>

启用此功能后,DataContractJsonSerializer 对象使用 TimeZoneInfo 类型(而不是 TimeZone 类型)来反序列化日期和时间数据。When this feature is enabled, a DataContractJsonSerializer object uses the TimeZoneInfo type instead of the TimeZone type to deserialize date and time data. TimeZoneInfo 支持多个调整规则,这样就可以使用历史时区数据;TimeZone 却不支持。TimeZoneInfo supports multiple adjustment rules, which makes it possible to work with historic time zone data; TimeZone does not.

若要详细了解 TimeZoneInfo 结构和时区调整,请参阅时区概述For more information on the TimeZoneInfo structure and time zone adjustments, see Time Zone Overview.

NetNamedPipeBinding 最佳匹配NetNamedPipeBinding best match

WCF 包含可以在客户端应用程序上设置以确保它们始终连接到服务的新应用设置,该服务在与它们请求的最匹配的 URI 上进行侦听。WCF has a new app setting that can be set on client applications to ensure they always connect to the service listening on the URI that best matches the one that they request. 将此应用设置设置为 false(默认值)时,客户端可以使用 NetNamedPipeBinding 尝试连接到服务,该服务在是所请求 URI 的子字符串的 URI 上进行侦听。With this app setting set to false (the default), it is possible for clients using NetNamedPipeBinding to attempt to connect to a service listening on a URI that is a substring of the requested URI.

例如,一个客户端尝试连接到在 net.pipe://localhost/Service1 处进行侦听的服务,但该计算机上使用管理员特权运行的另一个服务在 net.pipe://localhost 处进行侦听。For example, a client tries to connect to a service listening at net.pipe://localhost/Service1, but a different service on that machine running with administrator privilege is listening at net.pipe://localhost. 将此应用设置设置为 false 时,客户端将尝试连接到错误的服务。With this app setting set to false, the client would attempt to connect to the wrong service. 将应用设置设置为 true 后,客户端将始终连接到最匹配的服务。After setting the app setting to true, the client will always connect to the best matching service.

备注

使用 NetNamedPipeBinding 的客户端基于服务的基址(如果存在)而不是完整终结点地址查找服务。Clients using NetNamedPipeBinding find services based on the service's base address (if it exists) rather than the full endpoint address. 若要确保此设置始终有效,则服务应使用唯一基址。To ensure this setting always works the service should use a unique base address.

若要启用此更改,将以下应用设置添加到客户端应用程序的 App.config 或 Web.config 文件中:To enable this change, add the following app setting to your client application's App.config or Web.config file:

<configuration>
    <appSettings>
        <add key="wcf:useBestMatchNamedPipeUri" value="true" />
    </appSettings>
</configuration>

SSL 3.0 不是默认协议SSL 3.0 is not a default protocol

结合使用 NetTcp 与传输安全和证书的凭据类型时,SSL 3.0 不再是用于协商安全连接的默认协议。When using NetTcp with transport security and a credential type of certificate, SSL 3.0 is no longer a default protocol used for negotiating a secure connection. 在大多数情况下,应该不会影响现有应用,因为 TLS 1.0 包含在 NetTcp 的协议列表中。In most cases, there should be no impact to existing apps, because TLS 1.0 is included in the protocol list for NetTcp. 所有现有客户端应该能够至少使用 TLS 1.0 协商连接。All existing clients should be able to negotiate a connection using at least TLS 1.0. 如果 Ssl3 必需,则使用以下配置机制之一将其添加到协商协议的列表。If Ssl3 is required, use one of the following configuration mechanisms to add it to the list of negotiated protocols.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

在 .NET Framework 4.6.2 中,Windows Presentation Foundation 在以下几个方面进行了增强:In the .NET Framework 4.6.2, Windows Presentation Foundation has been enhanced in the following areas:

组排序Group sorting

使用 CollectionView 对象对数据进行分组的应用程序现在可以显式声明如何对组进行排序。An application that uses a CollectionView object to group data can now explicitly declare how to sort the groups. 显式排序可解决在应用动态添加或删除组,或在它更改分组中包含的项属性的值时出现的非直观排序问题。Explicit sorting addresses the problem of non-intuitive ordering that occurs when an app dynamically adds or removes groups, or when it changes the value of item properties involved in grouping. 它还可通过将分组属性比较从完整集合排序移动到组排序来改善组创建过程的性能。It can also improve the performance of the group creation process by moving comparisons of the grouping properties from the sort of the full collection to the sort of the groups.

为支持组排序,新的 GroupDescription.SortDescriptionsGroupDescription.CustomSort 属性描述如何对 GroupDescription 对象生成的组的集合进行排序。To support group sorting, the new GroupDescription.SortDescriptions and GroupDescription.CustomSort properties describe how to sort the collection of groups produced by the GroupDescription object. 这类似于同名 ListCollectionView 属性描述如何对数据项进行排序的方式。This is analogous to the way the identically named ListCollectionView properties describe how to sort the data items.

PropertyGroupDescription 类的两个新静态属性:CompareNameAscendingCompareNameDescending,可用于最常见的情况。Two new static properties of the PropertyGroupDescription class, CompareNameAscending and CompareNameDescending, can be used for the most common cases.

例如,下面的 XAML 按年龄分组数据,按升序对年龄组排序,并按姓氏分组每个年龄组内的项。For example, the following XAML groups data by age, sort the age groups in ascending order, and group the items within each age group by last name.

<GroupDescriptions>
     <PropertyGroupDescription
         PropertyName="Age"
         CustomSort=
              "{x:Static PropertyGroupDescription.CompareNamesAscending}"/>
     </PropertyGroupDescription>
</GroupDescriptions>

<SortDescriptions>
     <SortDescription PropertyName="LastName"/>
</SortDescriptions>

屏幕键盘支持Soft keyboard support

在可采用文本输入的控件接收触摸输入时,通过自动调用和解除 Windows 10 中新的屏幕键盘,屏幕键盘支持可在 WPF 应用程序中启用焦点跟踪。Soft Keyboard support enables focus tracking in a WPF applications by automatically invoking and dismissing the new Soft Keyboard in Windows 10 when the touch input is received by a control that can take textual input.

在 .NET framework 的早期版本中,WPF 应用程序不能在不禁用 WPF 笔/触摸手势支持的情况下选择加入焦点跟踪。In previous versions of the .NET Framework, WPF applications cannot opt into the focus tracking without disabling WPF pen/touch gesture support. 因此,WPF 应用程序必须选择完整的 WPF 触摸支持或依赖于 Windows 鼠标提升。As a result, WPF applications must choose between full WPF touch support or rely on Windows mouse promotion.

按监视器 DPIPer-monitor DPI

为了支持最近激增的 WPF 应用程序高 DPI 和混合 DPI 环境,.NET Framework 4.6.2 中的 WPF 启用了按监视器 DPI 感知。To support the recent proliferation of high-DPI and hybrid-DPI environments for WPF apps, WPF in the .NET Framework 4.6.2 enables per-monitor awareness. 有关如何使 WPF 应用成为按监视器 DPI 感知的详细信息,请参阅 GitHub 上的示例和开发人员指南See the samples and developer guide on GitHub for more information about how to enable your WPF app to become per-monitor DPI aware.

在 .NET framework 的早期版本中,WPF 应用为系统 DPI 感知。In previous versions of the .NET Framework, WPF apps are system-DPI aware. 换而言之,应用程序的 UI 由操作系统相应地进行缩放,具体取决于在其上呈现应用的监视器的 DPI。In other words, the application's UI is scaled by the OS as appropriate, depending on the DPI of the monitor on which the app is rendered.

对于在 .NET Framework 4.6.2 控制下运行的应用程序,可以在应用程序配置文件的 <runtime> 部分中添加配置语句,在 WPF 应用程序中禁用按监视器 DPI 更改,如下所示:For apps running under the .NET Framework 4.6.2, you can disable per-monitor DPI changes in WPF apps by adding a configuration statement to the <runtime> section of your application configuration file, as follows:

<runtime>
   <AppContextSwitchOverrides value="Switch.System.Windows.DoNotScaleForDpiChanges=false"/>
</runtime>

Windows Workflow Foundation (WF)Windows Workflow Foundation (WF)

在 .NET Framework 4.6.2 中,Windows Workflow Foundation 在以下几个方面进行了增强:In the .NET Framework 4.6.2, Windows Workflow Foundation has been enhanced in the following area:

在重新托管的 WF 设计器中支持 C# 表达式和 IntelliSenseSupport for C# expressions and IntelliSense in the Re-hosted WF Designer

自 .NET Framework 4.5 起,WF 支持在 Visual Studio 设计器和代码工作流中使用 C# 表达式。Starting with the .NET Framework 4.5, WF supports C# expressions in both the Visual Studio Designer and in code workflows. 重新托管的工作流设计器是 WF 的一项重要功能,允许工作流设计器位于 Visual Studio 外部的应用程序中(如 WPF 中)。The Re-hosted Workflow Designer is a key feature of WF that allows for the Workflow Designer to be in an application outside Visual Studio (for example, in WPF). Windows Workflow Foundation 提供在重新托管的工作流设计器中支持 C# 表达式和 IntelliSense 的功能。Windows Workflow Foundation provides the ability to support C# expressions and IntelliSense in the Re-hosted Workflow Designer. 有关详细信息,请参阅 Windows Workflow Foundation 博客For more information, see the Windows Workflow Foundation blog.

Availability of IntelliSense when a customer rebuilds a workflow project from Visual Studio 在低于 .NET Framework 4.6.2 的 .NET Framework 版本中,当客户通过 Visual Studio 重新生成工作流项目时,WF 设计器 IntelliSense 会中断。Availability of IntelliSense when a customer rebuilds a workflow project from Visual Studio In versions of the .NET Framework prior to the .NET Framework 4.6.2, WF Designer IntelliSense is broken when a customer rebuilds a workflow project from Visual Studio. 虽然项目生成成功,但在设计器中找不到该工作流类型,并且来自 IntelliSense 的缺少工作流类型的警告会出现在错误列表窗口中。While the project build is successful, the workflow types are not found on the designer, and warnings from IntelliSense for the missing workflow types appear in the Error List window. .NET Framework 4.6.2 解决了这个问题,并让 IntelliSense 可供使用。The .NET Framework 4.6.2 addresses this issue and makes IntelliSense available.

启用了工作流跟踪的工作流 V1 应用程序现以 FIPS 模式运行Workflow V1 applications with Workflow Tracking on now run under FIPS-mode

已启用 FIPS 兼容模式的计算机现在可以成功运行启用了工作流跟踪的工作流版本 1 样式的应用程序。Machines with FIPS Compliance Mode enabled can now successfully run a workflow Version 1-style application with Workflow tracking on. 若要启用此方案,必须对 app.config 文件进行以下更改:To enable this scenario, you must make the following change to your app.config file:

<add key="microsoft:WorkflowRuntime:FIPSRequired" value="true" />

如果未启用此方案,运行应用程序将继续生成异常,并显示消息“此实现不是 Windows 平台 FIPS 验证的加密算法的一部分”。If this scenario is not enabled, running the application continues to generate an exception with the message, "This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms."

结合使用动态更新和 Visual Studio 工作流设计器时的工作流改进Workflow Improvements when using Dynamic Update with Visual Studio Workflow Designer

工作流设计器、流程图活动设计器和其他工作流活动设计器现在已成功加载并显示调用 DynamicUpdateServices.PrepareForUpdate 方法后已保存的工作流。The Workflow Designer, FlowChart Activity Designer, and other Workflow Activity Designers now successfully load and display workflows that have been saved after calling the DynamicUpdateServices.PrepareForUpdate method. 在 .NET Framework 4.6.2 之前的 .NET Framework 版本中,在 Visual Studio 中为调用 DynamicUpdateServices.PrepareForUpdate 后保存的工作流加载 XAML 文件可能会导致以下问题:In versions of the .NET Framework before .NET Framework 4.6.2, loading a XAML file in Visual Studio for a workflow that has been saved after calling DynamicUpdateServices.PrepareForUpdate can result in the following issues:

  • 工作流设计器无法正确加载 XAML 文件(当 ViewStateData.Id 位于行末尾处时)。The Workflow Designer can't load the XAML file correctly (when the ViewStateData.Id is at the end of the line).

  • 流程图活动设计器或其他工作流活动设计器可能在其默认位置显示所有对象,与附加的属性值相反。Flowchart Activity Designer or other Workflow Activity Designers may display all objects in their default locations as opposed to attached property values.

ClickOnceClickOnce

除现已支持的 1.0 协议以外,ClickOnce 已更新为还支持 TLS 1.1 和 TLS 1.2。ClickOnce has been updated to support TLS 1.1 and TLS 1.2 in addition to the 1.0 protocol, which it already supports. ClickOnce 会自动检测哪种协议必需;启用 TLS 1.1 和 1.2 支持无需 ClickOnce 应用程序中的任何额外步骤。ClickOnce automatically detects which protocol is required; no extra steps within the ClickOnce application are required to enable TLS 1.1 and 1.2 support.

将 Windows 窗体和 WPF 应用转换为 UWP 应用Converting Windows Forms and WPF apps to UWP apps

Windows 现在提供将现有 Windows 桌面应用(包括 WPF 和 Windows 窗体应用)引入通用 Windows 平台 (UWP) 的功能。Windows now offers capabilities to bring existing Windows desktop apps, including WPF and Windows Forms apps, to the Universal Windows Platform (UWP). 这项技术充当的是一座桥梁,使你能够逐渐将现有代码库迁移到 UWP,从而将你的应用引入所有 Windows 10 设备。This technology acts as a bridge by enabling you to gradually migrate your existing code base to UWP, thereby bringing your app to all Windows 10 devices.

转换后的桌面应用会获得应用标识,类似于 UWP 应用的应用标识,该标识使 UWP API 可访问以启用如动态磁贴和通知等功能。Converted desktop apps gain an app identity similar to the app identity of UWP apps, which makes UWP APIs accessible to enable features such as Live Tiles and notifications. 应用的行为将继续像以前一样,并作为完全信任应用运行。The app continues to behave as before and runs as a full trust app. 应用转换之后,可将应用容器进程添加到现有的完全信任进程,以添加自适应用户界面。Once the app is converted, an app container process can be added to the existing full trust process to add an adaptive user interface. 将所有功能移动到应用容器进程后,可以删除完全信任进程,并且可对所有 Windows 10 设备提供新的 UWP 应用。When all functionality is moved to the app container process, the full trust process can be removed and the new UWP app can be made available to all Windows 10 devices.

调试改进Debugging improvements

非托管调试 API 在 .NET Framework 4.6.2 中得到了增强,可在引发 NullReferenceException 时执行附加分析,让你能够确定单行源代码中哪个变量是 nullThe unmanaged debugging API has been enhanced in the .NET Framework 4.6.2 to perform additional analysis when a NullReferenceException is thrown so that it is possible to determine which variable in a single line of source code is null. 为支持此方案,已将以下 API 添加到非托管调试 API。To support this scenario, the following APIs have been added to the unmanaged debugging API.

.NET Framework 4.6.1 中的新增功能What's new in .NET Framework 4.6.1

.NET Framework 4.6.1 在以下几个领域新增了功能:The .NET Framework 4.6.1 includes new features in the following areas:

若要详细了解 .NET Framework 4.6.1,请参阅以下主题:For more information on the .NET Framework 4.6.1, see the following topics:

加密:支持包含 ECDSA 在内的 X509 证书Cryptography: Support for X509 certificates containing ECDSA

.NET Framework 4.6 添加了针对 X509 证书的 RSACng 支持。.NET Framework 4.6 added RSACng support for X509 certificates. .NET Framework 4.6.1 现已开始支持 ECDSA(椭圆曲线数字签名算法)X509 证书。The .NET Framework 4.6.1 adds support for ECDSA (Elliptic Curve Digital Signature Algorithm) X509 certificates.

ECDSA 可提供更好的性能,是一种比 RSA 更安全的加密算法,从而可在传输层安全性 (TLS) 性能和可伸缩性十分重要的情况下提供极佳选择。ECDSA offers better performance and is a more secure cryptography algorithm than RSA, providing an excellent choice where Transport Layer Security (TLS) performance and scalability is a concern. .NET Framework 实现可将调用包装到现有 Windows 功能中。The .NET Framework implementation wraps calls into existing Windows functionality.

下面的示例代码展示了如何利用 .NET Framework 4.6.1 中新增的 ECDSA X509 证书支持,轻松生成字节流的签名。The following example code shows how easy it is to generate a signature for a byte stream by using the new support for ECDSA X509 certificates included in the .NET Framework 4.6.1.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class Net461Code
{
    public static byte[] SignECDsaSha512(byte[] data, X509Certificate2 cert)
    {
        using (ECDsa privateKey = cert.GetECDsaPrivateKey())
        {
            return privateKey.SignData(data, HashAlgorithmName.SHA512);
        }
    }

    public static byte[] SignECDsaSha512(byte[] data, ECDsa privateKey)
    {
        return privateKey.SignData(data, HashAlgorithmName.SHA512);
    }
}
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Public Class Net461Code
    Public Shared Function SignECDsaSha512(data As Byte(), cert As X509Certificate2) As Byte()
        Using privateKey As ECDsa = cert.GetECDsaPrivateKey()
            Return privateKey.SignData(data, HashAlgorithmName.SHA512)
        End Using
    End Function

    Public Shared Function SignECDsaSha512(data As Byte, privateKey As ECDsa) As Byte()
        Return privateKey.SignData(data, HashAlgorithmName.SHA512)
    End Function
End Class

这与在 .NET Framework 4.6 中生成签名所需的代码形成了鲜明对比。This offers a marked contrast to the code needed to generate a signature in .NET Framework 4.6.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class Net46Code
{
    public static byte[] SignECDsaSha512(byte[] data, X509Certificate2 cert)
    {
        // This would require using cert.Handle and a series of p/invokes to get at the
        // underlying key, then passing that to a CngKey object, and passing that to
        // new ECDsa(CngKey).  It's a lot of work.
        throw new Exception("That's a lot of work...");
    }

    public static byte[] SignECDsaSha512(byte[] data, ECDsa privateKey)
    {
        // This way works, but SignData probably better matches what you want.
        using (SHA512 hasher = SHA512.Create())
        {
            byte[] signature1 = privateKey.SignHash(hasher.ComputeHash(data));
        }

        // This might not be the ECDsa you got!
        ECDsaCng ecDsaCng = (ECDsaCng)privateKey;
        ecDsaCng.HashAlgorithm = CngAlgorithm.Sha512;
        return ecDsaCng.SignData(data);
    }
}   
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Public Class Net46Code
    Public Shared Function SignECDsaSha512(data As Byte(), cert As X509Certificate2) As Byte()
        ' This would require using cert.Handle and a series of p/invokes to get at the
        ' underlying key, then passing that to a CngKey object, and passing that to
        ' new ECDsa(CngKey).  It's a lot of work.
        Throw New Exception("That's a lot of work...")
    End Function

    Public Shared Function SignECDsaSha512(data As Byte(), privateKey As ECDsa) As Byte()
        ' This way works, but SignData probably better matches what you want.
        Using hasher As SHA512 = SHA512.Create()
            Dim signature1 As Byte() = privateKey.SignHash(hasher.ComputeHash(data))
        End Using

        ' This might not be the ECDsa you got!
        Dim ecDsaCng As ECDsaCng = CType(privateKey, ECDsaCng)
        ecDsaCng.HashAlgorithm = CngAlgorithm.Sha512
        Return ecDsaCng.SignData(data)
    End Function
End Class   

ADO.NETADO.NET

以下内容已添加到 ADO.NET 中:The following have been added to ADO.NET:

针对硬件保护密钥的 Always Encrypted 支持Always Encrypted support for hardware protected keys

ADO.NET 现在支持以本机方式在硬件安全模块 (HSM) 中存储始终加密列主密钥。ADO.NET now supports storing Always Encrypted column master keys natively in Hardware Security Modules (HSMs). 借助此支持,客户可以利用存储在 HSM 中的非对称密钥,而不必编写自定义列主密钥存储提供程序并在应用程序中注册它们。With this support, customers can leverage asymmetric keys stored in HSMs without having to write custom column master key store providers and registering them in applications.

客户需要在应用服务器或客户端计算机上安装 HSM 供应商提供的 CSP 提供程序或 CNG 密钥存储提供程序,才能访问使用存储在 HSM 中的列主密钥保护的始终加密数据。Customers need to install the HSM vendor-provided CSP provider or CNG key store providers on the app servers or client computers in order to access Always Encrypted data protected with column master keys stored in a HSM.

改进了 AlwaysOn 的 MultiSubnetFailover 连接行为Improved MultiSubnetFailover connection behavior for AlwaysOn

SqlClient 现在可自动提供与 AlwaysOn 可用性组 (AG) 之间的更快连接。SqlClient now automatically provides faster connections to an AlwaysOn Availability Group (AG). 它以透明方式检测应用程序是否连接到不同子网上的 AlwaysOn 可用性组 (AG),快速发现当前的活动服务器并提供与服务器之间的连接。It transparently detects whether your application is connecting to an AlwaysOn availability group (AG) on a different subnet and quickly discovers the current active server and provides a connection to the server. 在此版本之前,应用程序必须将连接字符串设置为包括 "MultisubnetFailover=true",以指示它已连接到 AlwaysOn 可用性组。Prior to this release, an application had to set the connection string to include "MultisubnetFailover=true" to indicate that it was connecting to an AlwaysOn Availability Group. 如果未将连接关键字设置为 true,则应用程序可能会在连接到 AlwaysOn 可用性组时遇到超时。Without setting the connection keyword to true, an application might experience a timeout while connecting to an AlwaysOn Availability Group. 使用此版本时,应用程序无需再将 MultiSubnetFailover 设置为 trueWith this release, an application does not need to set MultiSubnetFailover to true anymore. 有关对 Always On 可用性组的 SqlClient 支持的详细信息,请参阅对高可用性、灾难恢复的 SqlClient 支持For more information about SqlClient support for Always On Availability Groups, see SqlClient Support for High Availability, Disaster Recovery.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

Windows Presentation Foundation 包括一些改进和更改。Windows Presentation Foundation includes a number of improvements and changes.

提升了性能Improved performance

在 .NET Framework 4.6.1 中,触控事件的触发延迟问题得到了解决。The delay in firing touch events has been fixed in the .NET Framework 4.6.1. 此外在快速输入过程中,在 RichTextBox 控件中输入不再占用呈现线程。In addition, typing in a RichTextBox control no longer ties up the render thread during fast input.

拼写检查改进Spell checking improvements

WPF 中的拼写检查器在 Windows 8.1 和更高版本上进行了更新,可利用操作系统支持对其他语言进行拼写检查。The spell checker in WPF has been updated on Windows 8.1 and later versions to leverage operating system support for spell-checking additional languages. 在 Windows 8.1 之前的 Windows 版本上,功能方面没有更改。There is no change in functionality on Windows versions prior to Windows 8.1.

与以前版本的 .NET Framework 一样,可通过按以下顺序查找信息来检测 TextBox 控件或 RichTextBox 块的语言:As in previous versions of the .NET Framework, the language for a TextBox control ora RichTextBox block is detected by looking for information in the following order:

  • xml:lang(如果存在)。xml:lang, if it is present.

  • 当前输入语言。Current input language.

  • 当前线程区域性。Current thread culture.

有关 WPF 中的语言支持的其他信息,请参阅有关 .NET Framework 4.6.1 功能的 WPF 博客文章For additional information on language support in WPF, see the WPF blog post on .NET Framework 4.6.1 features.

针对每用户自定义词典的附加支持Additional support for per-user custom dictionaries

在 .NET Framework 4.6.1 中,WPF 可识别全局注册的自定义字典。In .NET Framework 4.6.1, WPF recognizes custom dictionaries that are registered globally. 除了能够针对每个控件注册它们,还提供了此功能。This capability is available in addition to the ability to register them per-control.

在以前版本的 WPF 中,自定义词典无法识别已排除的单词和自动更正列表。In previous versions of WPF, custom dictionaries did not recognize Excluded Words and AutoCorrect lists. 在 Windows 8.1 和 Windows 10 上,通过使用可以置于 %AppData%\Microsoft\Spelling\<language tag> 目录下的文件来支持它们。They are supported on Windows 8.1 and Windows 10 through the use of files that can be placed under the %AppData%\Microsoft\Spelling\<language tag> directory. 以下规则适用于这些文件:The following rules apply to these files:

  • 这些文件应具有扩展名 .dic(用于已添加的单词)、.exc(用于已排除的单词)或 .acl(用于自动更正)。The files should have extensions of .dic (for added words), .exc (for excluded words), or .acl (for AutoCorrect).

  • 这些文件应是以字节顺序标记 (BOM) 开头的 UTF-16 LE 纯文本。The files should be UTF-16 LE plaintext that starts with the Byte Order Mark (BOM).

  • 每行应包含一个单词(位于已添加和已排除的单词列表中),或是其中用竖线 ("|") 分隔单词的自动更正对(位于自动更正单词列表中)。Each line should consist of a word (in the added and excluded word lists), or an autocorrect pair with the words separated by a vertical bar ("|") (in the AutoCorrect word list).

  • 这些文件被视为只读,不会由系统进行修改。These files are considered read-only and are not modified by the system.

备注

WPF 拼写检查 API 不直接支持这些新文件格式,在应用程序中向 WPF 提供自定义词典应继续使用 .lex 文件。These new file-formats are not directly supported by the WPF spell checking APIs, and the custom dictionaries supplied to WPF in applications should continue to use .lex files.

示例Samples

Microsoft/WPF 示例 GitHub 存储库中具有大量的 WPF 示例。There are a number of WPF samples on the Microsoft/WPF-Samples GitHub repository. 可通过向我们发送拉取请求或建立 GitHub 问题来帮助我们改进示例。Help us improve our samples by sending us a pull-request or opening a GitHub issue.

DirectX 扩展DirectX extensions

WPF 包括一个 NuGet 包,它提供 D3DImage 的新实现,从而使你可以轻松地与 DX10 和 Dx11 内容进行互操作。WPF includes a NuGet package that provides new implementations of D3DImage that make it easy for you to interoperate with DX10 and Dx11 content. 此包的代码已开放源代码,在 GitHub 上提供。The code for this package has been open sourced and is available on GitHub.

Windows Workflow Foundation:事务Windows Workflow Foundation: Transactions

Transaction.EnlistPromotableSinglePhase 方法现在可以使用 MSDTC 以外的分布式事务管理器来提升事务。The Transaction.EnlistPromotableSinglePhase method can now use a distributed transaction manager other than MSDTC to promote the transaction. 可通过将 GUID 事务提升程序标识符指定为新的 Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification, Guid) 重载来实现此目的。You do this by specifying a GUID transaction promoter identifier to the new Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification, Guid) overload . 如果此操作成功,则会对事务的功能施加一些限制。If this operation is successful, there are limitations placed on the capabilities of the transaction. 非 MSDTC 事务提升程序登记之后,以下方法会引发 TransactionPromotionException,因为这些方法需要提升到 MSDTC:Once a non-MSDTC transaction promoter is enlisted, the following methods throw a TransactionPromotionException because these methods require promotion to MSDTC:

非 MSDTC 事务提升程序登记之后,它必须使用它定义的协议来用于将来的持久登记。Once a non-MSDTC transaction promoter is enlisted, it must be used for future durable enlistments by using protocols that it defines. 事务提升程序的 Guid 可以使用 PromoterType 属性来获取。The Guid of the transaction promoter can be obtained by using the PromoterType property. 当事务提升时,事务提升程序会提供表示提升令牌的 Byte 数组。When the transaction promotes, the transaction promoter provides a Byte array that represents the promoted token. 应用程序可以使用 GetPromotedToken 方法获取非 MSDTC 提升事务的提升令牌。An application can obtain the promoted token for a non-MSDTC promoted transaction with the GetPromotedToken method.

Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification, Guid) 重载的用户必须遵循特定调用序列,才能使提升操作成功完成。Users of the new Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification, Guid) overload must follow a specific call sequence in order for the promotion operation to complete successfully. 这些规则记录在该方法的文档中。These rules are documented in the method's documentation.

分析Profiling

非托管分析 API 在以下方面得到了增强:The unmanaged profiling API has been enhanced as follows:

  • 更好地支持在 ICorProfilerInfo7 接口中访问 PDB。Better support for accessing PDBs in the ICorProfilerInfo7 interface.

    在 ASP.NET Core 中,由 Roslyn 在内存中编译程序集正变得更加常见。In ASP.NET Core, it is becoming much more common for assemblies to be compiled in-memory by Roslyn. 对于创建分析工具的开发人员而言,这意味着过去在磁盘上进行序列化的 PDB 可能会不再存在。For developers making profiling tools, this means that PDBs that historically were serialized on disk may no longer be present. 对于代码覆盖率或逐行性能分析这类任务,分析器工具通常使用 PDB 将代码映射回源行。Profiler tools often use PDBs to map code back to source lines for tasks such as code coverage or line-by-line performance analysis. ICorProfilerInfo7 接口现在包含两种新方法(ICorProfilerInfo7::GetInMemorySymbolsLengthICorProfilerInfo7::ReadInMemorySymbols),可为这些探查器工具提供对内存中 PDB 数据的访问。通过使用新 API,探查器可以采用字节数组形式获取内存中 PDB 的内容,然后对它进行处理或将它序列化到磁盘。The ICorProfilerInfo7 interface now includes two new methods, ICorProfilerInfo7::GetInMemorySymbolsLength and ICorProfilerInfo7::ReadInMemorySymbols, to provide these profiler tools with access to the in-memory PDB data, By using the new APIs, a profiler can obtain the contents of an in-memory PDB as a byte array and then process it or serialize it to disk.

  • 使用 ICorProfiler 接口可更好地检测。Better instrumentation with the ICorProfiler interface.

    使用 ICorProfiler API 的 ReJit 功能进行动态检测的分析器现在可以修改某些元数据。Profilers that are using the ICorProfiler APIs ReJit functionality for dynamic instrumentation can now modify some metadata. 以前这类工具可以随时检测 IL,但只能在模块加载时修改元数据。Previously such tools could instrument IL at any time, but metadata could only be modified at module load time. 因为 IL 引用元数据,所以这会限制可以进行的检测的种类。Because IL refers to metadata, this limited the kinds of instrumentation that could be done. 我们通过添加 ICorProfilerInfo7::ApplyMetaData 方法来支持在模块加载之后编辑元数据的子集(特别是通过添加新的 AssemblyRefTypeRefTypeSpecMemberRefMemberSpecUserString 记录),解除了其中一些限制。We have lifted some of those limits by adding the ICorProfilerInfo7::ApplyMetaData method to support a subset of metadata edits after the module loads, in particular by adding new AssemblyRef, TypeRef, TypeSpec, MemberRef, MemberSpec, and UserString records. 通过此更改可以进行范围广得多的动态检测。This change makes a much broader range of on-the-fly instrumentation possible.

本机映像生成器 (NGEN) PDBNative Image Generator (NGEN) PDBs

跨计算机事件跟踪允许客户在计算机 A 上分析一个程序,并在计算机 B 上查看具有源行映射的分析数据。通过使用以前版本的 .NET Framework,用户会将所有模块和本机映像从分析计算机复制到包含 IL PDB 的分析计算机来创建源到本机映射。Cross-machine event tracing allows customers to profile a program on Machine A and look at the profiling data with source line mapping on Machine B. Using previous versions of the .NET Framework, the user would copy all the modules and native images from the profiled machine to the analysis machine that contains the IL PDB to create the source-to-native mapping. 虽然此过程在文件相对较小(如用于手机应用程序)时可能工作良好,但是文件在桌面系统上可能非常大,需要很长时间来进行复制。While this process may work well when the files are relatively small, such as for phone applications, the files can be very large on desktop systems and require significant time to copy.

借助 Ngen PDB,NGen 可以创建包含 IL 到本机映射的 PDB,而无需依赖于 IL PDB。With Ngen PDBs, NGen can create a PDB that contains the IL-to-native mapping without a dependency on the IL PDB. 在我们的跨计算机事件跟踪方案中,只需将计算机 A 生成的本机映像 PDB 复制到计算机 B,并使用调试接口访问 API 读取 IL PDB 的源到 IL 映射和本机映像 PDB 的 IL 到本机映射。In our cross-machine event tracing scenario, all that is needed is to copy the native image PDB that is generated by Machine A to Machine B and to use Debug Interface Access APIs to read the IL PDB's source-to-IL mapping and the native image PDB's IL-to-native mapping. 组合这两个映射可提供源到本机映射。Combining both mappings provides a source-to-native mapping. 由于本机映像 PDB 远小于所有模块和本机映像,因此从计算机 A 复制到计算机 B 的过程要快得多。Since the native image PDB is much smaller than all the modules and native images, the process of copying from Machine A to Machine B is much faster.

.NET 2015 的新增功能What's new in .NET 2015

.NET 2015 引入了 .NET Framework 4.6 和 .NET Core。.NET 2015 introduces the .NET Framework 4.6 and .NET Core. 一些新功能两者都适用,而另一些功能则是 .NET Framework 4.6 或 .NET Core 的专属功能。Some new features apply to both, and other features are specific to .NET Framework 4.6 or .NET Core.

  • ASP.NET CoreASP.NET Core

    .NET 2015 包括 ASP.NET Core,是一个用于生成基于云的新式应用的精益 .NET 实现。.NET 2015 includes ASP.NET Core, which is a lean .NET implementation for building modern cloud-based apps. ASP.NET Core 是模块化的,因此你可以仅包括应用程序所需的那些功能。ASP.NET Core is modular so you can include only those features that are needed in your application. 其可承载于 IIS 上或自承载于自定义过程中,并且你可以在同一服务器上运行具有不同版本 .NET Framework 的应用。It can be hosted on IIS or self-hosted in a custom process, and you can run apps with different versions of the .NET Framework on the same server. 它包括为云部署而设计的新环境配置系统。It includes a new environment configuration system that is designed for cloud deployment.

    MVC、Web API 和 Web Pages 统一至称为 MVC 6 的单个 Framework。MVC, Web API, and Web Pages are unified into a single framework called MVC 6. 通过 Visual Studio 2015 或更高版本中的新工具生成 ASP.NET Core 应用。You build ASP.NET Core apps through tools in Visual Studio 2015 or later. 现有应用程序将在新 .NET Framework 上工作;但是,若要生成使用 MVC 6 或 SignalR 3 的应用,则必须使用 Visual Studio 2015 或更高版本中的项目系统。Your existing applications will work on the new .NET Framework; however to build an app that uses MVC 6 or SignalR 3, you must use the project system in Visual Studio 2015 or later.

    有关信息,请参阅 ASP.NET CoreFor information, see ASP.NET Core.

  • ASP.NET 更新ASP.NET Updates

    • 基于任务的 API,用于异步响应刷新Task-based API for Asynchronous Response Flushing

      ASP.NET 现在提供一个基于任务的简单 API HttpResponse.FlushAsync 用于异步响应刷新,它允许通过使用你的语言的 async/await 支持来异步刷新响应。ASP.NET now provides a simple task-based API for asynchronous response flushing, HttpResponse.FlushAsync, that allows responses to be flushed asynchronously by using your language's async/await support.

    • 模型绑定支持 Task 返回方法Model binding supports task-returning methods

      在 .NET Framework 4.5 中,ASP.NET 增加了模型绑定功能,启用了一种以代码为中心的可扩展方法,用于在 Web 窗体页面和用户控件中执行基于 CRUD 的数据操作。In the .NET Framework 4.5, ASP.NET added the Model Binding feature that enabled an extensible, code-focused approach to CRUD-based data operations in Web Forms pages and user controls. 模型绑定系统现在支持 Task-returning 模型绑定方法。The Model Binding system now supports Task-returning model binding methods. 此功能使得 Web 窗体开发人员在使用较新版本的 ORM(包括实体框架)时,能获得异步的可伸缩性优点以及数据绑定系统的易用性。This feature allows Web Forms developers to get the scalability benefits of async with the ease of the data-binding system when using newer versions of ORMs, including the Entity Framework.

      异步模型绑定由 aspnet:EnableAsyncModelBinding 配置设置控制。Async model binding is controlled by the aspnet:EnableAsyncModelBinding configuration setting.

      <appSettings>
          <add key=" aspnet:EnableAsyncModelBinding" value="true|false" />
      </appSettings>
      

      在定位 .NET Framework 4.6 的应用程序中,默认值为 trueOn apps the target the .NET Framework 4.6, it defaults to true. 在定位旧版 .NET Framework 但在 .NET Framework 4.6 上运行的应用程序中,默认值为 falseOn apps running on the .NET Framework 4.6 that target an earlier version of the .NET Framework, it is false by default. 可以通过将配置设置设置为 true 来启用它。It can be enabled by setting the configuration setting to true.

    • HTTP/2 支持 (Windows 10)HTTP/2 Support (Windows 10)

      HTTP/2 是新版的 HTTP 协议,提供更好的连接利用率(客户端和服务器之间的往返更少),从而减少为用户加载网页的延迟。HTTP/2 is a new version of the HTTP protocol that provides much better connection utilization (fewer round-trips between client and server), resulting in lower latency web page loading for users. 网页(而不是服务)从 HTTP/2 中获益最多,因为该协议优化多个作为单个体验的一部分进行请求的项目。Web pages (as opposed to services) benefit the most from HTTP/2, since the protocol optimizes for multiple artifacts being requested as part of a single experience. 已向 .NET Framework 4.6 中的 ASP.NET 添加了 HTTP/2 支持。HTTP/2 support has been added to ASP.NET in .NET Framework 4.6. 因为网络功能存在于多个层,所以 Windows、IIS 和 ASP.NET 中均需要新功能以启用 HTTP/2。Because networking functionality exists at multiple layers, new features were required in Windows, in IIS, and in ASP.NET to enable HTTP/2. 必须在 Windows 10 上运行,以便将 HTTP/2 与 ASP.NET 搭配使用。You must be running on Windows 10 to use HTTP/2 with ASP.NET.

      HTTP/2 也受到支持,默认情况下在使用 System.Net.Http.HttpClient API 的 Windows 10 通用 Windows 平台 (UWP) 上使用。HTTP/2 is also supported and on by default for Windows 10 Universal Windows Platform (UWP) apps that use the System.Net.Http.HttpClient API.

      为了提供一种方法来使用 ASP.NET 应用程序中的 PUSH_PROMISE 功能,已向 HttpResponse 类添加了一种具有两个重载(PushPromise(String)PushPromise(String, String, NameValueCollection))的新方法。In order to provide a way to use the PUSH_PROMISE feature in ASP.NET applications, a new method with two overloads, PushPromise(String) and PushPromise(String, String, NameValueCollection), has been added to the HttpResponse class.

      备注

      尽管 ASP.NET Core 支持 HTTP/2,不过尚未添加针对 PUSH PROMISE 功能的支持。While ASP.NET Core supports HTTP/2, support for the PUSH PROMISE feature has not yet been added.

      浏览器和 Web 服务器(Windows 上的 IIS)执行所有工作。The browser and the web server (IIS on Windows) do all the work. 无需为用户执行任何繁重任务。You don't have to do any heavy-lifting for your users.

      大多数主要浏览器都支持 HTTP/2,因此很可能你的用户将从 HTTP/2 支持中受益(如果你的服务器支持它)。Most of the major browsers support HTTP/2, so it's likely that your users will benefit from HTTP/2 support if your server supports it.

    • 对令牌绑定协议的支持Support for the Token Binding Protocol

      Microsoft 和 Google 一直在针对身份验证的新方法进行合作,这种方法称为令牌绑定协议Microsoft and Google have been collaborating on a new approach to authentication, called the Token Binding Protocol. 前提是罪犯可以盗取并使用身份验证令牌(在你的浏览器缓存中)以访问本应安全的资源(例如你的银行帐户),而无需知道密码或任何其他特权。The premise is that authentication tokens (in your browser cache) can be stolen and used by criminals to access otherwise secure resources (e.g. your bank account) without requiring your password or any other privileged knowledge. 新协议旨在缓解此问题。The new protocol aims to mitigate this problem.

      令牌绑定协议将在 Windows 10 中作为浏览器功能实现。The Token Binding Protocol will be implemented in Windows 10 as a browser feature. ASP.NET 应用将参与该协议,以使身份验证令牌验证为合法。ASP.NET apps will participate in the protocol, so that authentication tokens are validated to be legitimate. 客户端和服务器实现建立由协议指定的端到端的保护。The client and the server implementations establish the end-to-end protection specified by the protocol.

    • 随机字符串哈希算法Randomized string hash algorithms

      .NET Framework 4.5 引入了随机字符串哈希算法.NET Framework 4.5 introduced a randomized string hash algorithm. 但是,由于某些 ASP.NET 功能依赖于稳定的哈希代码,因此 ASP.NET 不支持该算法。However, it was not supported by ASP.NET because of some ASP.NET features depended on a stable hash code. 在 .NET Framework 4.6 中,现在支持随机字符串哈希算法。In .NET Framework 4.6, randomized string hash algorithms are now supported. 若要启用此功能,请使用 aspnet:UseRandomizedStringHashAlgorithm 配置设置。To enable this feature, use the aspnet:UseRandomizedStringHashAlgorithm config setting.

      <appSettings>
          <add key="aspnet:UseRandomizedStringHashAlgorithm" value="true|false" />
      </appSettings>
      
  • ADO.NETADO.NET

    ADO.NET 现在支持 SQL Server 2016 社区技术预览版 2 (CTP2) 中提供的 Always Encrypted 功能。ADO .NET now supports the Always Encrypted feature available in SQL Server 2016 Community Technology Preview 2 (CTP2). 借助 Always Encrypted,SQL Server 可对加密数据执行操作,并且最重要的是,加密密钥与应用程序一起驻留在客户的受信任环境内,而不是驻留在服务器上。With Always Encrypted, SQL Server can perform operations on encrypted data, and best of all the encryption key resides with the application inside the customer’s trusted environment and not on the server. Always Encrypted 可确保客户数据的安全,因此 DBA 没有纯文本数据的访问权限。Always Encrypted secures customer data so DBAs do not have access to plain text data. 数据的加密和解密都在驱动程序级别以透明方式执行,从而将现有应用程序必须做出的更改减至最少。Encryption and decryption of data happens transparently at the driver level, minimizing changes that have to be made to existing applications. 有关详细信息,请参阅 Always Encrypted(数据库引擎)Always Encrypted(客户端开发)For details, see Always Encrypted (Database Engine) and Always Encrypted (client development).

  • 托管代码的 64 位 JIT 编译器64-bit JIT Compiler for managed code

    .NET Framework 4.6 采用新版 64 位 JIT 编译器(最初代码名为 RyuJIT)。.NET Framework 4.6 features a new version of the 64-bit JIT compiler (originally code-named RyuJIT). 新的 64 位编译器相较旧的 64 位 JIT 编译器具有显著的性能提升。The new 64-bit compiler provides significant performance improvements over the older 64-bit JIT compiler. 新的 64 位编译器针对 .NET Framework 4.6 上运行的 64 位进程而启用。The new 64-bit compiler is enabled for 64-bit processes running on top of .NET Framework 4.6. 如果你的应用被编译为 64 位或 AnyCPU 并在 64 位操作系统上运行,则它将在 64 位进程中运行。Your app will run in a 64-bit process if it is compiled as 64-bit or AnyCPU and is running on a 64-bit operating system. 虽然已采取谨慎的措施来使到新编译器的转换尽可能透明,但行为也可能发生变化。While care has been taken to make the transition to the new compiler as transparent as possible, changes in behavior are possible. 我们希望能够直接了解有关使用新的 JIT 编译器时遇到的任何问题。We would like to hear directly about any issues encountered when using the new JIT compiler. 如果遇到可能与新的 64 位 JIT 编译器相关的问题,请通过 Microsoft Connect 与我们联系。Please contact us through Microsoft Connect if you encounter an issue that may be related to the new 64-bit JIT compiler.

    新的 64 位 JIT 编译器还包括硬件 SIMD 加速功能,结合 System.Numerics 命名空间中支持 SIMD 的类型使用时,可以获得良好的性能提升。The new 64-bit JIT compiler also includes hardware SIMD acceleration features when coupled with SIMD-enabled types in the System.Numerics namespace, which can yield good performance improvements.

  • 程序集加载程序改进Assembly loader improvements

    通过在加载相应的 NGEN 映像后卸载 IL 程序集,程序集加载程序现在能更有效地利用内存。The assembly loader now uses memory more efficiently by unloading IL assemblies after a corresponding NGEN image is loaded. 此更改会降低虚拟内存(这对诸如 Visual Studio 等的大型 32 位应用特别有益),还会节省物理内存。This change decreases virtual memory, which is particularly beneficial for large 32-bit apps (such as Visual Studio), and also saves physical memory.

  • 基类库更改Base class library changes

    为了启用关键方案,已向 .NET Framework 4.6 添加了许多新 API。Many new APIs have been added around to .NET Framework 4.6 to enable key scenarios. 这些包括以下更改和添加:These include the following changes and additions:

    • IReadOnlyCollection<T> 实现IReadOnlyCollection<T> implementations

      其他集合实现 IReadOnlyCollection<T>,例如 Queue<T>Stack<T>Additional collections implement IReadOnlyCollection<T> such as Queue<T> and Stack<T>.

    • CultureInfo.CurrentCulture 和 CultureInfo.CurrentUICultureCultureInfo.CurrentCulture and CultureInfo.CurrentUICulture

      CultureInfo.CurrentCultureCultureInfo.CurrentUICulture 属性现在是读写而不是只读。The CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture properties are now read-write rather than read-only. 如果你向这些属性分配一个新 CultureInfo 对象,则由 Thread.CurrentThread.CurrentCulture 属性定义的当前线程区域性和由 Thread.CurrentThread.CurrentUICulture 属性定义在当前 UI 线程区域性也会更改。If you assign a new CultureInfo object to these properties, the current thread culture defined by the Thread.CurrentThread.CurrentCulture property and the current UI thread culture defined by the Thread.CurrentThread.CurrentUICulture properties also change.

    • 垃圾回收 (GC) 增强功能Enhancements to garbage collection (GC)

      GC 类现在包括允许你在执行关键路径期间禁止垃圾回收的 TryStartNoGCRegionEndNoGCRegion 方法。The GC class now includes TryStartNoGCRegion and EndNoGCRegion methods that allow you to disallow garbage collection during the execution of a critical path.

      GC.Collect(Int32, GCCollectionMode, Boolean, Boolean) 方法的新重载允许你控制小型对象堆和大型对象堆是否均扫频和压缩或仅扫频。A new overload of the GC.Collect(Int32, GCCollectionMode, Boolean, Boolean) method allows you to control whether both the small object heap and the large object heap are swept and compacted or swept only.

    • 启用了 SIMD 的类型SIMD-enabled types

      System.Numerics 命名空间现在包括许多支持 SIMD 的类型,如 Matrix3x2Matrix4x4PlaneQuaternionVector2Vector3Vector4The System.Numerics namespace now includes a number of SIMD-enabled types, such as Matrix3x2, Matrix4x4, Plane, Quaternion, Vector2, Vector3, and Vector4.

      由于新的 64 位 JIT 编译器还包括硬件 SIMD 加速功能,将支持 SIMD 的类型与新的 64 位 JIT 编译器一起使用时,会带来特别显著的性能提升。Because the new 64-bit JIT compiler also includes hardware SIMD acceleration features, there are especially significant performance improvements when using the SIMD-enabled types with the new 64-bit JIT compiler.

    • 加密更新Cryptography updates

      System.Security.Cryptography API 更新为支持 Windows CNG 加密 APIThe System.Security.Cryptography API is being updated to support the Windows CNG cryptography APIs. 以前版本的 .NET Framework 完全依赖于早期版本的 Windows 加密 API,以用作 System.Security.Cryptography 实现的基础。Previous versions of the .NET Framework have relied entirely on an earlier version of the Windows Cryptography APIs as the basis for the System.Security.Cryptography implementation. 我们已经请求支持 CNG API,因为它支持现代加密算法,这对某些类别的应用十分重要。We have had requests to support the CNG API, since it supports modern cryptography algorithms, which are important for certain categories of apps.

      .NET Framework 4.6 包括以下新的增强功能以支持 Windows CNG 加密 API:.NET Framework 4.6 includes the following new enhancements to support the Windows CNG cryptography APIs:

      • X509 证书(System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPublicKey(System.Security.Cryptography.X509Certificates.X509Certificate2)System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(System.Security.Cryptography.X509Certificates.X509Certificate2))的一组扩展方法,如果可能,它们将返回基于 CNG 的实现,而不返回基于 CAPI 的实现。A set of extension methods for X509 Certificates, System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPublicKey(System.Security.Cryptography.X509Certificates.X509Certificate2) and System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(System.Security.Cryptography.X509Certificates.X509Certificate2), that return a CNG-based implementation rather than a CAPI-based implementation when possible. (一些智能卡等仍需要 CAPI,并由 API 处理回退)。(Some smartcards, etc., still require CAPI, and the APIs handle the fallback).

      • System.Security.Cryptography.RSACng 类,该类提供 RSA 算法的 CNG 实现。The System.Security.Cryptography.RSACng class, which provides a CNG implementation of the RSA algorithm.

      • RSA API 的增强功能,常见操作不再需要转换。Enhancements to the RSA API so that common actions no longer require casting. 例如,使用 X509Certificate2 对象加密数据需要类似以前版本的 .NET Framework 中的以下代码。For example, encrypting data using an X509Certificate2 object requires code like the following in previous versions of the .NET Framework.

        RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
        byte[] oaepEncrypted = rsa.Encrypt(data, true);
        byte[] pkcs1Encrypted = rsa.Encrypt(data, false);
        
        Dim rsa As RSACryptoServiceProvider = CType(cert.PrivateKey, RSACryptoServiceProvider)
        Dim oaepEncrypted() As Byte = rsa.Encrypt(data, True)
        Dim pkcs1Encrypted() As Byte = rsa.Encrypt(data, False)
        

        可采用如下方式重写在 .NET Framework 4.6 中使用新加密 API 的代码以避免转换。Code that uses the new cryptography APIs in .NET Framework 4.6 can be rewritten as follows to avoid the cast.

        RSA rsa = cert.GetRSAPrivateKey();
        if (rsa == null)
           throw new InvalidOperationException("An RSA certificate was expected");
        
        byte[] oaepEncrypted = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
        byte[] pkcs1Encrypted = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
        
        Dim rsa As RSA = cert.GetRSAPrivateKey()
        If rsa Is Nothing Then
           Throw New InvalidOperationException("An RSA certificate was expected")
         End If
        
        Dim oaepEncrypted() As Byte = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1)
        Dim pkcs1Encrypted() As Byte = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1)
        
    • 支持将日期和时间与 UNIX 时间相互转换Support for converting dates and times to or from Unix time

      以下新方法已添加到 DateTimeOffset 结构,以支持将日期和时间转换为 UNIX 时间或将 UNIX 时间转换为日期和时间:The following new methods have been added to the DateTimeOffset structure to support converting date and time values to or from Unix time:

    • 兼容性开关Compatibility switches

      AppContext 类添加一个新的兼容性功能,使库编写器可为其用户提供统一的新功能选择退出机制。The new AppContext class adds a new compatibility feature that enables library writers to provide a uniform opt-out mechanism for new functionality for their users. 它在组件之间建立松耦合的协定,以便与选择退出请求进行通信。It establishes a loosely-coupled contract between components in order to communicate an opt-out request. 对现有功能进行更改时,此功能通常很重要。This capability is typically important when a change is made to existing functionality. 相反,已有新功能隐式选择加入。Conversely, there is already an implicit opt-in for new functionality.

      使用 AppContext,库定义并公开兼容性开关,而依赖于这些开关的代码可以设置这些开关以影响库行为。With AppContext, libraries define and expose compatibility switches, while code that depends on them can set those switches to affect the library behavior. 默认情况下,库提供新功能;如果设置了开关,则只更改新功能(即,它们提供以前的功能)。By default, libraries provide the new functionality, and they only alter it (that is, they provide the previous functionality) if the switch is set.

      应用程序(或库)可以声明相关库定义的开关的值(始终是 Boolean 值)。An application (or a library) can declare the value of a switch (which is always a Boolean value) that a dependent library defines. 该开关始终隐式 falseThe switch is always implicitly false. 将此开关设置为 true 将启用它。Setting the switch to true enables it. 将此开关显式设置为 false 将提供新行为。Explicitly setting the switch to false provides the new behavior.

      AppContext.SetSwitch("Switch.AmazingLib.ThrowOnException", true);
      
      AppContext.SetSwitch("Switch.AmazingLib.ThrowOnException", True)
      

      库必须检查使用者是否已声明该开关的值,并且相应地作用于它。The library must check if a consumer has declared the value of the switch and then appropriately act on it.

      if (!AppContext.TryGetSwitch("Switch.AmazingLib.ThrowOnException", out shouldThrow))
      {
          // This is the case where the switch value was not set by the application.
          // The library can choose to get the value of shouldThrow by other means.
          // If no overrides nor default values are specified, the value should be 'false'.
          // A false value implies the latest behavior.
      }
      
      // The library can use the value of shouldThrow to throw exceptions or not.
      if (shouldThrow)
      {
          // old code
      }
      else
      {
          // new code
      }
      
      If Not AppContext.TryGetSwitch("Switch.AmazingLib.ThrowOnException", shouldThrow) Then
          ' This is the case where the switch value was not set by the application.
          ' The library can choose to get the value of shouldThrow by other means.
          ' If no overrides nor default values are specified, the value should be 'false'.
          ' A false value implies the latest behavior.
      End If
      
      ' The library can use the value of shouldThrow to throw exceptions or not.
      If shouldThrow Then
          ' old code
      Else
          ' new code
      End If
      

      使用一致的开关格式是有益的,因为它们是由库公开的正式协定。It's beneficial to use a consistent format for switches, since they are a formal contract exposed by a library. 以下是两种明显的格式。The following are two obvious formats.

      • Switch.namespace.switchnameSwitch.namespace.switchname

      • Switch.library.switchnameSwitch.library.switchname

    • 更改为基于任务的异步模式 (TAP)Changes to the task-based asynchronous pattern (TAP)

      对于面向 .NET Framework 4.6、TaskTask<TResult> 对象的应用,请继承调用线程的区域性和 UI 区域性。For apps that target the .NET Framework 4.6, Task and Task<TResult> objects inherit the culture and UI culture of the calling thread. 面向早期 .NET Framework 版本或不面向特定版本的 .NET Framework 的应用的行为不受影响。The behavior of apps that target previous versions of the .NET Framework, or that do not target a specific version of the .NET Framework, is unaffected. 有关详细信息,请参阅 CultureInfo 类主题中的“区域性和基于任务的异步操作”一节。For more information, see the "Culture and task-based asynchronous operations" section of the CultureInfo class topic.

      System.Threading.AsyncLocal<T> 类允许你表示对于给定异步控制流(如 async 方法)来说是本地数据的环境数据。The System.Threading.AsyncLocal<T> class allows you to represent ambient data that is local to a given asynchronous control flow, such as an async method. 它可用于跨线程保存数据。It can be used to persist data across threads. 你还可以定义一个回调方法,该回调方法在环境数据发生变化时就会发出通知,而不论环境数据发生变化的原因是 AsyncLocal<T>.Value 属性显式更改还是线程遇到上下文转换。You can also define a callback method that is notified whenever the ambient data changes either because the AsyncLocal<T>.Value property was explicitly changed, or because the thread encountered a context transition.

      三种便利方法(Task.CompletedTaskTask.FromCanceledTask.FromException)已添加到基于任务的异步模式 (TAP),以返回处于特定状态的已完成任务。Three convenience methods, Task.CompletedTask, Task.FromCanceled, and Task.FromException, have been added to the task-based asynchronous pattern (TAP) to return completed tasks in a particular state.

      NamedPipeClientStream 类现在支持与其新的 ConnectAsync 进行异步通信。The NamedPipeClientStream class now supports asynchronous communication with its new ConnectAsync. 方法。method.

    • EventSource 现在支持写入事件日志EventSource now supports writing to the Event log

      除了在计算机上创建的任何现有 ETW 会话外,现在你还可以使用 EventSource 类将管理或操作消息记录到事件日志中。You now can use the EventSource class to log administrative or operational messages to the event log, in addition to any existing ETW sessions created on the machine. 在过去,你必须使用 Microsoft.Diagnostics.Tracing.EventSource NuGet 包才能实现此功能。In the past, you had to use the Microsoft.Diagnostics.Tracing.EventSource NuGet package for this functionality. 此功能现在内置于 .NET Framework 4.6 中。This functionality is now built-into .NET Framework 4.6.

      NuGet 包和 .NET Framework 4.6 都更新了以下功能:Both the NuGet package and .NET Framework 4.6 have been updated with the following features:

      • 动态事件Dynamic events

        允许在不创建事件方法的情况下“在运行过程中”定义事件。Allows events defined "on the fly" without creating event methods.

      • 丰富的负载Rich payloads

        允许将专门特性化的类和数组以及基元类型作为负载传递Allows specially attributed classes and arrays as well as primitive types to be passed as a payload

      • 活动跟踪Activity tracking

        使“开始”和“停止”事件用 ID 标记在它们之间发生的事件,以表示当前处于活动状态的所有活动。Causes Start and Stop events to tag events between them with an ID that represents all currently active activities.

      为了支持这些功能,已将重载的 Write 方法添加到了 EventSource 类。To support these features, the overloaded Write method has been added to the EventSource class.

  • Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

    • HDPI 改进HDPI improvements

      在 .NET Framework 4.6 中,WPF 现提供更出色的 HDPI 支持。HDPI support in WPF is now better in the .NET Framework 4.6. 已对布局舍入进行了更改,以减少带边框的控件中的剪切实例。Changes have been made to layout rounding to reduce instances of clipping in controls with borders. 默认情况下,仅当你的 TargetFrameworkAttribute 设置为 .NET 4.6 时才启用此功能。By default, this feature is enabled only if your TargetFrameworkAttribute is set to .NET 4.6. 对于定位旧版 Framework,但在 .NET Framework 4.6 上运行的应用程序,可以在 app.config 文件的 <runtime> 部分中添加下面的代码行,从而选择启用新行为:Applications that target earlier versions of the framework but are running on the .NET Framework 4.6 can opt in to the new behavior by adding the following line to the <runtime> section of the app.config file:

      <AppContextSwitchOverrides
      value="Switch.MS.Internal.DoNotApplyLayoutRoundingToMarginsAndBorderThickness=false"
      />
      

      跨越具有不同 DPI 设置(多 DPI 设置)的多个监视器的 WPF 窗口现在完全呈现,且没有涂黑区域。WPF windows straddling multiple monitors with different DPI settings (Multi-DPI setup) are now completely rendered without blacked-out regions. 可以通过将下面的行添加到 app.config 文件的 <appSettings> 部分来选择退出此行为,以禁用此新行为:You can opt out of this behavior by adding the following line to the <appSettings> section of the app.config file to disable this new behavior:

      <add key="EnableMultiMonitorDisplayClipping" value="true"/>
      

      已向 System.Windows.Input.Cursor 添加了对基于 DPI 设置自动加载右侧光标的支持。Support for automatically loading the right cursor based on DPI setting has been added to System.Windows.Input.Cursor.

    • 触摸更好Touch is better

      在 .NET Framework 4.6 中,客户在 Connect 中报告的触控服务导致不可预测行为发生的问题得到了解决。Customer reports on Connect that touch produces unpredictable behavior have been addressed in the .NET Framework 4.6. Windows 应用商店应用程序和 WPF 应用程序的双击阈值现在与 Windows 8.1 及更高版本中的相同。The double tap threshold for Windows Store applications and WPF applications is now the same in Windows 8.1 and above.

    • 透明子窗口支持Transparent child window support

      .NET Framework 4.6 中的 WPF 支持在 Windows 8.1 及更高版本中使用透明子窗口。WPF in the .NET Framework 4.6 supports transparent child windows in Windows 8.1 and above. 这使得你可以在顶层窗口中创建非矩形的透明子窗口。This allows you to create non-rectangular and transparent child windows in your top-level windows. 你可以通过将 HwndSourceParameters.UsesPerPixelTransparency 属性设置为 true 启用此功能。You can enable this feature by setting the HwndSourceParameters.UsesPerPixelTransparency property to true.

  • Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)

    • SSL 支持SSL support

      将 NetTcp 用于传输安全和客户端身份验证时,除了 SSL 3.0 和 TLS 1.0,WCF 现在还支持 SSL 版本 TLS 1.1 和 TLS 1.2。WCF now supports SSL version TLS 1.1 and TLS 1.2, in addition to SSL 3.0 and TLS 1.0, when using NetTcp with transport security and client authentication. 现在可选择要使用的协议,或禁用旧的次要安全协议。It is now possible to select which protocol to use, or to disable old lesser secure protocols. 可以通过设置 SslProtocols 属性或通过将以下内容添加到配置文件来完成此操作。This can be done either by setting the SslProtocols property or by adding the following to a configuration file.

      <netTcpBinding>
          <binding>
            <security mode= "None|Transport|Message|TransportWithMessageCredential" >
                <transport clientCredentialType="None|Windows|Certificate"
                          protectionLevel="None|Sign|EncryptAndSign"
                          sslProtocols="Ssl3|Tls1|Tls11|Tls12">
                  </transport>
            </security>
          </binding>
      </netTcpBinding>
      
    • 使用不同的 HTTP 连接发送消息Sending messages using different HTTP connections

      WCF 现在允许用户确保使用不同的基础 HTTP 连接发送特定消息。WCF now allows users to ensure certain messages are sent using different underlying HTTP connections. 有两种方法可以实现此目的:There are two ways to do this:

      • 使用连接组名称前缀Using a connection group name prefix

        用户可以指定 WCF 将用作连接组名称前缀的字符串。Users can specify a string that WCF will use as a prefix for the connection group name. 使用不同的基础 HTTP 连接发送具有不同前缀的两个消息。Two messages with different prefixes are sent using different underlying HTTP connections. 通过将键/值对添加到消息的 Message.Properties 属性来设置前缀。You set the prefix by adding a key/value pair to the message's Message.Properties property. 键是“HttpTransportConnectionGroupNamePrefix”,值是所需的前缀。The key is "HttpTransportConnectionGroupNamePrefix"; the value is the desired prefix.

      • 使用不同的通道工厂Using different channel factories

        用户还可以启用一种功能,以确保使用由不同通道工厂所创建通道发送的消息将使用不同的基础 HTTP 连接。Users can also enable a feature that ensures that messages sent using channels created by different channel factories will use different underlying HTTP connections. 若要启用此功能,用户必须将以下 appSetting 设置为 trueTo enable this feature, users must set the following appSetting to true:

        <appSettings>
            <add key="wcf:httpTransportBinding:useUniqueConnectionPoolPerFactory" value="true" />
        </appSettings>
        
  • Windows Workflow Foundation (WWF)Windows Workflow Foundation (WWF)

    现在可以指定当请求超时之前存在某个未完成的“非协议”书签时,工作流服务针对无序操作请求将保持的秒数。You can now specify the number of seconds a workflow service will hold on to an out-of-order operation request when there is an outstanding "non-protocol" bookmark before timing out the request. “非协议”书签是不与未完成的“接收”活动相关的书签。A "non-protocol" bookmark is a bookmark that is not related to outstanding Receive activities. 某些活动会在其实现内创建非协议书签,因此非协议书签的存在可能不太明显。Some activities create non-protocol bookmarks within their implementation, so it may not be obvious that a non-protocol bookmark exists. 此类书签包括“状态”和“选取”。These include State and Pick. 因此,如果你拥有使用状态机实现的工作流服务,或包含“选取”活动的工作流服务,你将很可能具有非协议书签。So if you have a workflow service implemented with a state machine or containing a Pick activity, you will most likely have non-protocol bookmarks. 通过将如下所示的行添加到 app.config 文件的 appSettings 部分来指定时间间隔:You specify the interval by adding a line like the following to the appSettings section of your app.config file:

    <add key="microsoft:WorkflowServices:FilterResumeTimeoutInSeconds" value="60"/>
    

    默认值为 60 秒。The default value is 60 seconds. 如果 value 设置为 0,则会立即拒绝无序请求并出现错误,错误文本如下所示:If value is set to 0, out-of-order requests are immediately rejected with a fault with text that looks like this:

    Operation 'Request3|{http://tempuri.org/}IService' on service instance with identifier '2b0667b6-09c8-4093-9d02-f6c67d534292' cannot be performed at this time. Please ensure that the operations are performed in the correct order and that the binding in use provides ordered delivery guarantees.
    

    当收到无序操作消息且没有非协议书签时,你将收到同一条消息。This is the same message that you receive if an out-of-order operation message is received and there are no non-protocol bookmarks.

    如果 FilterResumeTimeoutInSeconds 元素的值为非零,且没有非协议书签并且超时间隔过期,则操作失败并出现超时消息。If the value of the FilterResumeTimeoutInSeconds element is non-zero, there are non-protocol bookmarks, and the timeout interval expires, the operation fails with a timeout message.

  • 事务Transactions

    你现在可以包含事务的分布式事务标识符,该事务导致了引发派生自 TransactionException 的异常。You can now include the distributed transaction identifier for the transaction that has caused an exception derived from TransactionException to be thrown. 通过将以下键添加到 app.config 文件的 appSettings 部分来完成此操作:You do this by adding the following key to the appSettings section of your app.config file:

    <add key="Transactions:IncludeDistributedTransactionIdInExceptionMessage" value="true"/>
    

    默认值为 falseThe default value is false.

  • 网络连接Networking

    • 套接字重用Socket reuse

      Windows 10 包括一个新的高可伸缩性网络算法,它能通过重用出站 TCP 连接的本地端口来更好地利用计算机资源。Windows 10 includes a new high-scalability networking algorithm that makes better use of machine resources by reusing local ports for outbound TCP connections. .NET Framework 4.6 支持新算法,这使得 .NET 应用可以充分利用新的行为。.NET Framework 4.6 supports the new algorithm, enabling .NET apps to take advantage of the new behavior. 在以前版本的 Windows 中,有人工并发连接限制(通常为 16,384,即动态端口范围的默认大小),这可能导致负载下的端口耗尽,从而限制了服务的可伸缩性。In previous versions of Windows, there was an artificial concurrent connection limit (typically 16,384, the default size of the dynamic port range), which could limit the scalability of a service by causing port exhaustion when under load.

      在 .NET Framework 4.6 中,添加了两个新 API,用于启用端口重用,有效撤消了并发连接方面的 64K 限制:In the .NET Framework 4.6, two new APIs have been added to enable port reuse, which effectively removes the 64K limit on concurrent connections:

      默认情况下,ServicePointManager.ReusePort 属性为 false,除非 HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 注册表项的 HWRPortReuseOnSocketBind 值设置为 0x1。By default, the ServicePointManager.ReusePort property is false unless the HWRPortReuseOnSocketBind value of the HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 registry key is set to 0x1. 若要对 HTTP 连接启用本地端口重用,请将 ServicePointManager.ReusePort 属性设置为 trueTo enable local port reuse on HTTP connections, set the ServicePointManager.ReusePort property to true. 这将导致来自 HttpClientHttpWebRequest 的所有传出 TCP 套接字连接使用新的 Windows 10 套接字选项 SO_REUSE_UNICASTPORT,该选项将启用本地端口重用。This causes all outgoing TCP socket connections from HttpClient and HttpWebRequest to use a new Windows 10 socket option, SO_REUSE_UNICASTPORT, that enables local port reuse.

      调用 Socket.SetSocketOption 等方法时,编写仅限套接字的应用程序的开发人员可以指定 System.Net.Sockets.SocketOptionName 选项,以便出站套接字在绑定期间重用本地端口。Developers writing a sockets-only application can specify the System.Net.Sockets.SocketOptionName option when calling a method such as Socket.SetSocketOption so that outbound sockets reuse local ports during binding.

    • 对国际域名和 PunyCode 的支持Support for international domain names and PunyCode

      一个新属性 IdnHost 已添加到了 Uri 类,以更好地支持国际域名和 PunyCode。A new property, IdnHost, has been added to the Uri class to better support international domain names and PunyCode.

  • 在 Windows 窗体控件中调整大小。Resizing in Windows Forms controls.

    此功能已在 .NET Framework 4.6 中展开,以包括绘制 UITypeEditor 时所使用的 Bounds 属性所指定的 DomainUpDownNumericUpDownDataGridViewComboBoxColumnDataGridViewColumnToolStripSplitButton 类型和矩形。This feature has been expanded in .NET Framework 4.6 to include the DomainUpDown, NumericUpDown, DataGridViewComboBoxColumn, DataGridViewColumn and ToolStripSplitButton types and the rectangle specified by the Bounds property used when drawing a UITypeEditor.

    这是一项可以选择使用的功能。This is an opt-in feature. 若要启用它,在应用程序配置 (app.config) 文件中将 EnableWindowsFormsHighDpiAutoResizing 元素设置为 trueTo enable it, set the EnableWindowsFormsHighDpiAutoResizing element to true in the application configuration (app.config) file:

    <appSettings>
        <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
    </appSettings>
    
  • 对代码页编码的支持Support for code page encodings

    .NET Core 主要支持 Unicode 编码,在代码页编码方面默认提供一定程度的支持。.NET Core primarily supports the Unicode encodings and by default provides limited support for code page encodings. 可以使用 Encoding.RegisterProvider 方法注册代码页编码,从而支持 .NET Framework 可用但 .NET Core 不支持的代码页编码。You can add support for code page encodings available in .NET Framework but unsupported in .NET Core by registering code page encodings with the Encoding.RegisterProvider method. 有关详细信息,请参阅 System.Text.CodePagesEncodingProviderFor more information, see System.Text.CodePagesEncodingProvider.

  • .NET Native.NET Native

    定位 .NET Core 且用 C# 或 Visual Basic 编写的 Windows 10 相关 Windows 应用程序可以利用将应用程序编译为本机代码(而非 IL)的新技术。Windows apps for Windows 10 that target .NET Core and are written in C# or Visual Basic can take advantage of a new technology that compiles apps to native code rather than IL. 它们所生成的应用程序具有启动和执行时间更快速的特点。They produce apps characterized by faster startup and execution times. 有关详细信息,请参阅使用 .NET Native 编译应用For more information, see Compiling Apps with .NET Native. 有关探讨与 JIT 编译和 NGEN 的差别以及对你的代码的意义的 .NET Native 概述,请参阅 .NET Native 和编译For an overview of .NET Native that examines how it differs from both JIT compilation and NGEN and what that means for your code, see .NET Native and Compilation.

    使用 Visual Studio 2015 或更高版本进行编译时,默认将应用程序编译为本机代码。Your apps are compiled to native code by default when you compile them with Visual Studio 2015 or later. 有关详细信息,请参阅 .NET Native 入门For more information, see Getting Started with .NET Native.

    为了支持调试 .NET Native 应用,已向非托管调试 API 添加大量新的接口和枚举。To support debugging .NET Native apps, a number of new interfaces and enumerations have been added to the unmanaged debugging API. 有关详细信息,请参阅调试(非托管 API 参考)主题。For more information, see the Debugging (Unmanaged API Reference) topic.

  • 开放源代码 .NET Framework 包Open-source .NET Framework packages

    .NET Core 包(如不可变集合)、SIMD API 以及网络 API(如在 System.Net.Http 命名空间中找到的网络 API)现在都可在 GitHub 上用作开放源代码程序包。.NET Core packages such as the immutable collections, SIMD APIs, and networking APIs such as those found in the System.Net.Http namespace are now available as open source packages on GitHub. 若要访问代码,请参阅 GitHub 上的 CoreFxTo access the code, see CoreFx on GitHub. 有关详细信息以及如何参与这些包,请参阅 .NET Core 和开放源代码GitHub 上的 .NET 主页For more information and how to contribute to these packages, see .NET Core and Open-Source, .NET Home Page on GitHub.

.NET Framework 4.5.2 中的新增功能What's new in .NET Framework 4.5.2

.NET Framework 4.5.1 中的新增功能What's new in .NET Framework 4.5.1

2014 年 4 月版更新April 2014 updates:

  • Visual Studio 2013 Update 2 包括对可移植类库模板的更新,以支持以下方案:Visual Studio 2013 Update 2 includes updates to the Portable Class Library templates to support these scenarios:

    • 你可以使用面向 Windows 8.1、Windows Phone 8.1 和 Windows Phone Silverlight 8.1 的可移植库中的 Windows 运行时 API。You can use Windows Runtime APIs in portable libraries that target Windows 8.1, Windows Phone 8.1, and Windows Phone Silverlight 8.1.

    • 在面向 Windows 8.1 或 Windows Phone 8.1 时,你可以在可移植库中包含 XAML(Windows.UI.XAML 类型)。You can include XAML (Windows.UI.XAML types) in portable libraries when you target Windows 8.1 or Windows Phone 8.1. 支持以下 XAML 模板:空白页、资源字典、模板控件和用户控件。The following XAML templates are supported: Blank Page, Resource Dictionary, Templated Control, and User Control.

    • 你可以创建可移植 Windows 运行时组件(.winmd 文件)以用于面向 Windows 8.1 和 Windows Phone 8.1 的应用商店应用。You can create a portable Windows Runtime component (.winmd file) for use in Store apps that target Windows 8.1 and Windows Phone 8.1.

    • 你可以重定 Windows 应用商店或 Windows Phone 应用商店类库(例如可移植类库)的目标。You can retarget a Windows Store or Windows Phone Store class library like a Portable Class Library.

    有关这些更改的详细信息,请参阅可移植类库For more information about these changes, see Portable Class Library.

  • .NET Framework 内容集现在包括 .NET Native 相关文档,这是一种用于生成和部署 Windows 应用程序的预编译技术。The .NET Framework content set now includes documentation for .NET Native, which is a precompilation technology for building and deploying Windows apps. 为了提升性能,.NET Native 将应用程序直接编译为本机代码,而不是中间语言 (IL)。.NET Native compiles your apps directly to native code, rather than to intermediate language (IL), for better performance. 有关详细信息,请参阅使用 .NET Native 编译应用For details, see Compiling Apps with .NET Native.

  • .NET Framework 引用源提供新的浏览体验和增强功能。The .NET Framework Reference Source provides a new browsing experience and enhanced functionality. 现在可以联机浏览 .NET Framework 源代码,下载引用以供脱机查看,并在调试时逐步执行源(包括修补程序和更新)。You can now browse through the .NET Framework source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging. 有关详细信息,请参阅日志 .NET 引用源的全新外观For more information, see the blog entry A new look for .NET Reference Source.

.NET Framework 4.5.1 基类中的新增功能和增强包括:New features and enhancements in the base classes in .NET Framework 4.5.1 include:

Windows 窗体的改进包括:Improvements to Windows Forms include:

  • 在 Windows 窗体控件中调整大小。Resizing in Windows Forms controls. 你可以使用系统 DPI 设置调整控件(例如,显示在属性网格中的图标)组件的大小,方法是使用应用的应用程序配置文件 (app.config) 中的条目选择使用该功能。You can use the system DPI setting to resize components of controls (for example, the icons that appear in a property grid) by opting in with an entry in the application configuration file (app.config) for your app. 此功能当前在以下 Windows 窗体控件中受支持:This feature is currently supported in the following Windows Forms controls:

    若要启用此功能,请将新 <appSettings> 元素添加到配置文件 (app.config) 并将 EnableWindowsFormsHighDpiAutoResizing 元素设置为 trueTo enable this feature, add a new <appSettings> element to the configuration file (app.config) and set the EnableWindowsFormsHighDpiAutoResizing element to true:

    <appSettings>
        <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
    </appSettings>
    

有关在 Visual Studio 2013 中调试 .NET Framework 应用程序的改进包括:Improvements when debugging your .NET Framework apps in Visual Studio 2013 include:

  • 返回 Visual Studio 调试器中的值。Return values in the Visual Studio debugger. 在 Visual Studio 2013 中调试托管应用程序时,“自动”窗口会显示方法的返回类型和值。When you debug a managed app in Visual Studio 2013, the Autos window displays return types and values for methods. 此信息可用于桌面、Windows 应用商店和 Windows Phone 应用程序。This information is available for desktop, Windows Store, and Windows Phone apps. 有关详细信息,请参阅检查方法调用的返回值For more information, see Examine return values of method calls.

  • 针对 64 位应用程序的“编辑并继续”。Edit and Continue for 64-bit apps. Visual Studio 2013 支持对桌面、Windows 应用商店和 Windows Phone 相关 64 位托管应用程序使用“编辑并继续”功能。Visual Studio 2013 supports the Edit and Continue feature for 64-bit managed apps for desktop, Windows Store, and Windows Phone. 现有的限制对 32 位和 64 位应用仍然有效(请参阅支持的代码更改 (C#) 文章的最后一节)。The existing limitations remain in effect for both 32-bit and 64-bit apps (see the last section of the Supported Code Changes (C#) article).

  • 异步识别调试。Async-aware debugging. 为了简化在 Visual Studio 2013 中调试异步应用程序,调用堆栈隐藏了编译器提供的基础结构代码以支持异步编程,并链入了逻辑父框架,以便你可以更加明确逻辑程序的执行情况。To make it easier to debug asynchronous apps in Visual Studio 2013, the call stack hides the infrastructure code provided by compilers to support asynchronous programming, and also chains in logical parent frames so you can follow logical program execution more clearly. “任务”窗口将替换“并行任务”窗口,并显示与特定断点相关的任务,还会显示应用程序中当前处于活动状态或计划状态的任何其他任务。A Tasks window replaces the Parallel Tasks window and displays tasks that relate to a particular breakpoint, and also displays any other tasks that are currently active or scheduled in the app. 可以在 .NET Framework 4.5.1 公告的“异步识别调试”一节中了解此功能。You can read about this feature in the "Async-aware debugging" section of the .NET Framework 4.5.1 announcement.

  • 改进对 Windows 运行时组件的异常支持。Better exception support for Windows Runtime components. 在 Windows 8.1 中,Windows 应用商店应用抛出的异常保留了导致异常抛出的错误的相关信息(甚至可跨语言)。In Windows 8.1, exceptions that arise from Windows Store apps preserve information about the error that caused the exception, even across language boundaries. 可以在 .NET Framework 4.5.1 公告的“Windows 应用商店应用开发”一节中了解此功能。You can read about this feature in the "Windows Store app development" section of the .NET Framework 4.5.1 announcement.

自 Visual Studio 2013 起,可以使用托管配置文件引导式优化工具 (Mpgo.exe) 来优化 Windows 8.x 应用商店应用和桌面应用程序。Starting with Visual Studio 2013, you can use the Managed Profile Guided Optimization Tool (Mpgo.exe) to optimize Windows 8.x Store apps as well as desktop apps.

有关 ASP.NET 4.5.1 中的新功能,请参阅适用于 Visual Studio 2013 的 ASP.NET 和 Web 工具发行说明.For new features in ASP.NET 4.5.1, see ASP.NET and Web Tools for Visual Studio 2013 Release Notes.

.NET Framework 4.5 中的新增功能What's new in .NET Framework 4.5

基类Base classes

  • 能够在部署期间通过检测并关闭 .NET Framework 4 应用程序来减少系统重启。Ability to reduce system restarts by detecting and closing .NET Framework 4 applications during deployment. 请参阅在 .NET Framework 4.5 安装期间减少系统重新启动See Reducing System Restarts During .NET Framework 4.5 Installations.

  • 支持 64 位平台上大于 2 GB 的数组。Support for arrays that are larger than 2 gigabytes (GB) on 64-bit platforms. 此功能可在应用程序配置文件中启用。This feature can be enabled in the application configuration file. 请参阅 <gcAllowVeryLargeObjects> 元素,它还列出了对对象大小和数组大小的其他限制。See the <gcAllowVeryLargeObjects> element, which also lists other restrictions on object size and array size.

  • 通过服务器的后台垃圾回收来改进性能。Better performance through background garbage collection for servers. 在 .NET Framework 4.5 中使用服务器垃圾回收功能时,后台垃圾回收功能会自动启用。When you use server garbage collection in the .NET Framework 4.5, background garbage collection is automatically enabled. 请参阅垃圾回收的基础主题的“后台服务器垃圾回收”一节。See the Background Server Garbage Collection section of the Fundamentals of Garbage Collection topic.

  • 后台实时 (JIT) 编译,可在多核处理器上使用此功能改进应用程序性能。Background just-in-time (JIT) compilation, which is optionally available on multi-core processors to improve application performance. 请参阅 ProfileOptimizationSee ProfileOptimization.

  • 可以限制正则表达式引擎在超时之前持续尝试解析正则表达式的时间。请参阅 Regex.MatchTimeout 属性。Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out. See the Regex.MatchTimeout property.

  • 定义应用程序域的默认区域性的能力。Ability to define the default culture for an application domain. 请参阅 CultureInfo 类。See the CultureInfo class.

  • Unicode (UTF-16) 编码的控制台支持。Console support for Unicode (UTF-16) encoding. 请参阅 Console 类。See the Console class.

  • 支持对区域性字符串排序和比较数据进行版本控制。Support for versioning of cultural string ordering and comparison data. 请参阅 SortVersion 类。See the SortVersion class.

  • 改进检索资源时的性能。Better performance when retrieving resources. 请参阅打包和部署资源See Packaging and Deploying Resources.

  • Zip 压缩改进,可减少压缩文件的大小。Zip compression improvements to reduce the size of a compressed file. 请参阅 System.IO.Compression 命名空间。See the System.IO.Compression namespace.

  • 可以通过 CustomReflectionContext 类自定义用于重写默认反射行为的反射上下文。Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

  • 在 Windows 8 上使用 System.Globalization.IdnMapping 类时支持应用程序国际化域名 (IDNA) 标准的 2008 版。Support for the 2008 version of the Internationalized Domain Names in Applications (IDNA) standard when the System.Globalization.IdnMapping class is used on Windows 8.

  • 在 Windows 8 上使用 .NET Framework 时,可以将字符串比较委托给操作系统(这将实现 Unicode 6.0)。Delegation of string comparison to the operating system, which implements Unicode 6.0, when the .NET Framework is used on Windows 8. 在其他平台上运行时,.NET Framework 包括其自己的字符串比较数据,这将实现 Unicode 5.x。When running on other platforms, the .NET Framework includes its own string comparison data, which implements Unicode 5.x. 请参阅 String 类和 SortVersion 类的“备注”部分。See the String class and the Remarks section of the SortVersion class.

  • 能够为每个应用程序域计算字符串的哈希代码。Ability to compute the hash codes for strings on a per application domain basis. 请参阅 <UseRandomizedStringHashAlgorithm> 元素See <UseRandomizedStringHashAlgorithm> Element.

  • 类型反射支持 TypeTypeInfo 类之间的拆分。Type reflection support split between Type and TypeInfo classes. 请参阅 .NET Framework 中用于 Windows 应用商店应用的反射See Reflection in the .NET Framework for Windows Store Apps.

Managed Extensibility Framework (MEF)Managed Extensibility Framework (MEF)

在 .NET Framework 4.5 中,Managed Extensibility Framework (MEF) 新增了以下功能:In the .NET Framework 4.5, the Managed Extensibility Framework (MEF) provides the following new features:

  • 对泛型类型的支持。Support for generic types.

  • 利用基于约定的编程模型,你可以基于命名约定而非特性创建各个部分。Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.

  • 多个范围。Multiple scopes.

  • 创建 Windows 8.x 应用商店应用时可以使用一部分 MEF。A subset of MEF that you can use when you create Windows 8.x Store apps. 此子集可作为 NuGet 库中的可下载程序包提供。This subset is available as a downloadable package from the NuGet Gallery. 若要安装此程序包,请在 Visual Studio 中打开项目,从“项目” 菜单中选择“管理 NuGet 包” ,然后联机搜索 Microsoft.Composition 程序包。To install the package, open your project in Visual Studio, choose Manage NuGet Packages from the Project menu, and search online for the Microsoft.Composition package.

有关详细信息,请参阅 Managed Extensibility Framework (MEF)For more information, see Managed Extensibility Framework (MEF).

异步文件操作Asynchronous file operations

在 .NET Framework 4.5 中,已向 C# 和 Visual Basic 语言添加新的异步功能。In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. 这些功能将添加用于执行异步操作的基于任务的模型。These features add a task-based model for performing asynchronous operations. 若要使用此新模型,请使用 I/O 类中的异步方法。To use this new model, use the asynchronous methods in the I/O classes. 请参阅异步文件 I/OSee Asynchronous File I/O.

工具Tools

在 .NET Framework 4.5 中,使用资源文件生成器 (Resgen.exe),可以通过 .NET Framework 程序集中嵌入的 .resources 文件创建用于 Windows 8.x 应用商店应用的 .resw 文件。In the .NET Framework 4.5, Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows 8.x Store apps from a .resources file embedded in a .NET Framework assembly. 有关详细信息,请参阅 Resgen.exe(资源文件生成器)For more information, see Resgen.exe (Resource File Generator).

利用按托管配置优化 (Mpgo.exe) 工具,你可以通过优化本机映像程序集来改进应用程序的启动时间、内存使用率(工作集大小)和吞吐量。Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. 该命令行工具会针对本机映像应用程序程序集生成配置文件数据。The command-line tool generates profile data for native image application assemblies. 请参阅 Mpgo.exe(按托管配置文件优化工具)See Mpgo.exe (Managed Profile Guided Optimization Tool). 自 Visual Studio 2013 起,可以使用 Mpgo.exe 优化 Windows 8.x 应用商店应用和桌面应用程序。Starting with Visual Studio 2013, you can use Mpgo.exe to optimize Windows 8.x Store apps as well as desktop apps.

并行计算Parallel computing

.NET Framework 4.5 新增了多项有关并行计算的功能和改进。The .NET Framework 4.5 provides several new features and improvements for parallel computing. 其中包括改进的性能、增强的控件、对异步编程的增强支持、新的数据流库以及对并行调试和性能分析的增强支持。These include improved performance, increased control, improved support for asynchronous programming, a new dataflow library, and improved support for parallel debugging and performance analysis. 请参阅“使用 .NET 进行并行编程”博客中的 .NET 4.5 中有关并行的新增功能条目。See the entry What’s New for Parallelism in .NET 4.5 in the Parallel Programming with .NET blog.

WebWeb

ASP.NET 4.5 和 4.5.1 为 Web 窗体、WebSocket 支持、异步处理程序、性能增强和许多其他功能添加了模型绑定。ASP.NET 4.5 and 4.5.1 add model binding for Web Forms, WebSocket support, asynchronous handlers, performance enhancements, and many other features. 有关更多信息,请参见以下资源:For more information, see the following resources:

网络连接Networking

.NET Framework 4.5 新增了 HTTP 应用程序的编程接口。The .NET Framework 4.5 provides a new programming interface for HTTP applications. 有关详细信息,请参阅新的 System.Net.HttpSystem.Net.Http.Headers 命名空间。For more information, see the new System.Net.Http and System.Net.Http.Headers namespaces.

还包含针对用于接受 WebSocket 连接并与之交互(通过使用现有 HttpListener 和相关类)的新编程接口的支持。Support is also included for a new programming interface for accepting and interacting with a WebSocket connection by using the existing HttpListener and related classes. 有关详细信息,请参阅新的 System.Net.WebSockets 命名空间和 HttpListener 类。For more information, see the new System.Net.WebSockets namespace and the HttpListener class.

此外,.NET Framework 4.5 新增了以下网络改进:In addition, the .NET Framework 4.5 includes the following networking improvements:

  • 与 RFC 兼容的 URI 支持。RFC-compliant URI support. 有关详细信息,请参阅 Uri 和相关类。For more information, see Uri and related classes.

  • 对国际域名 (IDN) 分析的支持。Support for Internationalized Domain Name (IDN) parsing. 有关详细信息,请参阅 Uri 和相关类。For more information, see Uri and related classes.

  • 对电子邮件地址国际化 (EAI) 的支持。Support for Email Address Internationalization (EAI). 有关更多信息,请参见 System.Net.Mail 命名空间。For more information, see the System.Net.Mail namespace.

  • 改进的 IPv6 支持。Improved IPv6 support. 有关更多信息,请参见 System.Net.NetworkInformation 命名空间。For more information, see the System.Net.NetworkInformation namespace.

  • 双重模式套接字支持。Dual-mode socket support. 有关更多信息,请参见 SocketTcpListener 类。For more information, see the Socket and TcpListener classes.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF)

在 .NET Framework 4.5 中,Windows Presentation Foundation (WPF) 在以下几个领域进行了更改和改进:In the .NET Framework 4.5, Windows Presentation Foundation (WPF) contains changes and improvements in the following areas:

  • 利用新的 Ribbon 控件,你可以实现承载快速访问工具栏、应用程序菜单和选项卡的功能区用户界面。The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.

  • 支持同步和异步数据验证的新 INotifyDataErrorInfo 接口。The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.

  • VirtualizingPanelDispatcher 类的新功能。New features for the VirtualizingPanel and Dispatcher classes.

  • 通过在非 UI 线程上访问集合,改进了在显示大型分组数据集时的性能。Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.

  • 针对静态属性的数据绑定、针对实现 ICustomTypeProvider 接口的自定义类型的数据绑定,以及从绑定表达式中检索数据绑定信息。Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface, and retrieval of data binding information from a binding expression.

  • 在值发生更改时重新定位数据(实时数据整理)。Repositioning of data as the values change (live shaping).

  • 能够检查项目容器的数据上下文是否已断开连接。Ability to check whether the data context for an item container is disconnected.

  • 能够设置属性更改和数据源更新之间的时间间隔。Ability to set the amount of time that should elapse between property changes and data source updates.

  • 改进了对实现弱事件模式的支持。Improved support for implementing weak event patterns. 此外,事件现在可以接受标记扩展。Also, events can now accept markup extensions.

Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)

为了更轻松地编写和维护 Windows Communication Foundation (WCF) 应用程序,.NET Framework 4.5 中新增了以下功能:In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

  • 简化生成的配置文件。Simplification of generated configuration files.

  • 对协定优先开发的支持。Support for contract-first development.

  • 能够更轻松地配置 ASP.NET 兼容模式。Ability to configure ASP.NET compatibility mode more easily.

  • 对默认传输属性值的更改,可减小你必须设置这些值的可能性。Changes in default transport property values to reduce the likelihood that you will have to set them.

  • XmlDictionaryReaderQuotas 类进行更新,可减小你必须手动为 XML 字典读取器配置配额的可能性。Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.

  • 作为生成过程的一部分,由 Visual Studio 验证 WCF 配置文件,以便你可以在运行应用程序之前检测配置错误。Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.

  • 新的异步流支持。New asynchronous streaming support.

  • 新的 HTTPS 协议映射,使你能够更轻松地通过 Internet Information Services (IIS) 在 HTTPS 上公开终结点。New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).

  • 能够通过将 ?singleWSDL 追加到服务 URL,来在单个 WSDL 文档中生成元数据。Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.

  • WebSockets 支持,通过端口 80 和 443 启用真正的双向通信,其性能特性与 TCP 传输类似。Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.

  • 对在代码中配置服务的支持。Support for configuring services in code.

  • XML 编辑器工具提示。XML Editor tooltips.

  • ChannelFactory 缓存支持。ChannelFactory caching support.

  • 二进制文件编码器压缩支持。Binary encoder compression support.

  • 对 UDP 传输的支持,这可使开发人员编写使用“发后不理”消息的服务。Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. 客户端向服务发送消息,且不希望从该服务获得响应。A client sends a message to a service and expects no response from the service.

  • 能够在使用 HTTP 传输和传输安全性时,支持单个 WCF 终结点上的多个身份验证模式。Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.

  • 对使用国际域名 (IDN) 的 WCF 服务的支持。Support for WCF services that use internationalized domain names (IDNs).

有关详细信息,请参阅 Windows Communication Foundation 中的新增功能For more information, see What's New in Windows Communication Foundation.

Windows Workflow Foundation (WF)Windows Workflow Foundation (WF)

在 .NET Framework 4.5 中,已向 Windows Workflow Foundation (WF) 添加多项新功能,包括:In the .NET Framework 4.5, several new features were added to Windows Workflow Foundation (WF), including:

  • 首次作为 .NET Framework 4.0.1(.NET Framework 4 平台更新 1)的一部分引入的状态机工作流。State machine workflows, which were first introduced as part of .NET Framework 4.0.1 (.NET Framework 4 Platform Update 1). 此更新包括可使开发人员创建状态机工作流的多个新类和活动。This update included several new classes and activities that enabled developers to create state machine workflows. 这些类和活动已针对 .NET Framework 4.5 更新为包含:These classes and activities were updated for the .NET Framework 4.5 to include:

    • 对状态设置断点的能力。The ability to set breakpoints on states.

    • 在工作流设计器中复制和粘贴转换的能力。The ability to copy and paste transitions in the workflow designer.

    • 对共享的触发器转换创建的设计器支持。Designer support for shared trigger transition creation.

    • 创建状态机工作流的活动,包括:StateMachineStateTransitionActivities for creating state machine workflows, including: StateMachine, State, and Transition.

  • 增强的工作流设计器功能如下:Enhanced Workflow Designer features such as the following:

    • Visual Studio 中增强的工作流搜索功能,包括“快速查找” 和“在文件中查找” 。Enhanced workflow search capabilities in Visual Studio, including Quick Find and Find in Files.

    • 将第二个子活动添加到容器活动中时自动创建“序列”活动以及在“序列”活动中包括这两个活动的能力。Ability to automatically create a Sequence activity when a second child activity is added to a container activity, and to include both activities in the Sequence activity.

    • 平移支持,可让工作流的可见部分发生更改,而无需使用滚动条。Panning support, which enables the visible portion of a workflow to be changed without using the scroll bars.

    • 新“文档大纲” 视图,它在树样式的大纲视图中显示工作流组件并允许在“文档大纲” 视图中选择组件。A new Document Outline view that shows the components of a workflow in a tree-style outline view and lets you select a component in the Document Outline view.

    • 向活动中添加批注的能力。Ability to add annotations to activities.

    • 通过使用工作流设计器定义和使用活动委托的能力。Ability to define and consume activity delegates by using the workflow designer.

    • 状态机和流程图工作流中活动和转换的自动连接和自动插入。Auto-connect and auto-insert for activities and transitions in state machine and flowchart workflows.

  • XAML 文件的单个元素中工作流的视图状态信息存储,以便你可以轻松定位和编辑视图状态信息。Storage of the view state information for a workflow in a single element in the XAML file, so you can easily locate and edit the view state information.

  • 可防止子活动持久化的 NoPersistScope 容器活动。A NoPersistScope container activity to prevent child activities from persisting.

  • 对 C# 表达式的支持:Support for C# expressions:

    • 使用 Visual Basic 的工作流项目将使用 Visual Basic 表达式,C# 工作流项目将使用 C# 表达式。Workflow projects that use Visual Basic will use Visual Basic expressions, and C# workflow projects will use C# expressions.

    • 在 Visual Studio 2010 中创建并具有 Visual Basic 表达式的 C# 工作流项目与使用 C# 表达式的 C# 工作流项目兼容。C# workflow projects that were created in Visual Studio 2010 and that have Visual Basic expressions are compatible with C# workflow projects that use C# expressions.

  • 版本控制增强功能:Versioning enhancements:

    • WorkflowIdentity 类,它提供了保留的工作流实例与其工作流定义之间的映射。The new WorkflowIdentity class, which provides a mapping between a persisted workflow instance and its workflow definition.

    • 同一主机中多个工作流版本的并行执行,包括 WorkflowServiceHostSide-by-side execution of multiple workflow versions in the same host, including WorkflowServiceHost.

    • 在动态更新中,修改保留的工作流实例的定义的能力。In Dynamic Update, the ability to modify the definition of a persisted workflow instance.

  • 协定优先工作流服务开发,它为自动生成活动以匹配现有服务协定提供支持。Contract-first workflow service development, which provides support for automatically generating activities to match an existing service contract.

有关详细信息,请参阅 Windows Workflow Foundation 中的新增功能For more information, see What's New in Windows Workflow Foundation.

适用于 Windows 8.x 应用商店应用的 .NET.NET for Windows 8.x Store apps

Windows 8.x 应用商店应用专为特定外形规格而设计,并利用 Windows 操作系统的强大技术支持。Windows 8.x Store apps are designed for specific form factors and leverage the power of the Windows operating system. 可以使用一部分 .NET Framework 4.5 或 4.5.1 生成用 C# 或 Visual Basic 编写的 Windows 相关 Windows 8.x 应用商店应用。A subset of the .NET Framework 4.5 or 4.5.1 is available for building Windows 8.x Store apps for Windows by using C# or Visual Basic. 该部分被称作适用于 Windows 8.x 应用商店应用的 .NET,详见概述This subset is called .NET for Windows 8.x Store apps and is discussed in an overview.

可移植类库Portable Class Libraries

利用 Visual Studio 2012(及更高版本)中的可移植类库项目,可以编写和生成在多个 .NET Framework 平台上运行的托管程序集。The Portable Class Library project in Visual Studio 2012 (and later versions) enables you to write and build managed assemblies that work on multiple .NET Framework platforms. 使用可移植类库项目,可以选择目标平台(如 Windows Phone 和适用于 Windows 8.x 应用商店应用的 .NET)。Using a Portable Class Library project, you choose the platforms (such as Windows Phone and .NET for Windows 8.x Store apps) to target. 项目中的可用类型和成员自动限制为这些平台中的公共类型和成员。The available types and members in your project are automatically restricted to the common types and members across these platforms. 有关详细信息,请参阅可移植类库For more information, see Portable Class Library.

请参阅See also