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


.NET Framework 4.8 是 .NET Framework 的最新版本,而且不會再發行其他版本。.NET Framework 4.8 is the last version of .NET Framework, and no further versions will be released. 不過,.NET Framework 將 繼續提供 每月安全性和可靠性錯誤修正的服務。However, .NET Framework will continue to be serviced with monthly security and reliability bug fixes. 此外,它仍會繼續隨附于 Windows,而且沒有計劃將它移除。Additionally, it will continue to be included with Windows, with no plans to remove it. 您不需要遷移 .NET Framework 的應用程式,但對於新的開發,請使用 .net 5.0 或更新版本You don't need to migrate your .NET Framework apps, but for new development, use .NET 5.0 or later.

本文摘要說明下列 .NET Framework 版本的重要新功能和增強功能:This article summarizes key new features and improvements in the following versions of .NET Framework:

此文章並不會提供每一個新功能的完整資料,且內容可能會隨時變更。This article does not provide comprehensive information about each new feature and is subject to change. 如需 .NET Framework 的一般資訊,請參閱 消費者入門For general information about .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, using NuGet, to expand platform support and 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 .NET Framework and Out-of-Band Releases. 查看 .NET Framework 的 NuGet 套件完整清單See a complete list of NuGet packages for .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 .NET Framework 4.x by adding many new fixes and several new features while remaining a very stable product.

下載並安裝 .NET Framework 4。8Download and install .NET Framework 4.8

您可以從下列位置下載 .NET Framework 4.8:You can download .NET Framework 4.8 from the following locations:

.NET Framework 4.8 可以安裝在 Windows 10、Windows 8.1、Windows 7 SP1,以及自 Windows Server 2008 R2 SP1 起的相對應伺服器平台上。.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 .NET Framework.

基底類別Base classes

降低對密碼編譯的 FIPS 影響Reduced FIPS impact on Cryptography. 在舊版 .NET Framework 中,受管理的密碼編譯提供者類別(例如在「 SHA256Managed CryptographicException FIPS 模式」中設定系統密碼編譯程式庫時,會擲回)。In previous versions of .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 為目標的應用程式中,下列受控密碼編譯類別在此案例中已不會再擲回 a 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 模式中不會擲回 CryptographyException (英文)。For 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. clrcompression.dll 的 .NET Framework 4.8 版本已更新為使用 ZLib 版本1.2.11,其中包含數個重要的改進和修正。The .NET Framework 4.8 version of 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 =
    healthBehavior ??= new ServiceHealthBehavior();
    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
  • 透過使用設定檔。By using a configuration file. 例如:For example:

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

您可以透過使用查詢參數 (例如 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:

查詢參數與範例: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

    指定觸發回應的百分比 {1 – 100} 與其 HTTP 回應碼 {200 – 599}。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 縮放比例」之平台上裝載之 HWNDs 與 Windows Forms 交互操作 (在高 DPI WPF 應用程式中) 的支援 (從 Windows 10 April 2018 Update 開始)。.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). 當裝載的 HWNDs 或 Windows Forms 控制項建立為「混合模式 DPI 縮放」視窗 (透過呼叫 SetThreadDpiHostingBehaviorSetThreadDpiAwarenessContext) 時,它們可以裝載在個別監視器 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 感知」的支援也允許在高 DPI 應用程式的原生視窗中裝載 WPF 控制項 (亦即,父項化)。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:

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

Common Language RuntimeCommon 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 中的 Just-In-Time (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 Framework 4.8 JIT 編譯器中包括對 .NET Core 2.1 JIT 編譯器進行的許多最佳化與所有錯誤 (Bug) 修正。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. 執行階段已針對 Native Image Generator (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 .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 .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.

RRSA.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())
   // Other code to execute using the RSA instance.
' Before .NET Framework 4.7.2
Using rsa = RSA.Create()
   ' 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-256 之類的 SHA-2 式 HMAC,如下列範例所示: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


支援 Web Forms 中的相依性插入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:

支援相同網站 CookieSupport 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:

   <httpCookies sameSite="Strict" />

您可以藉由修改網頁組態檔,為 FormsAuthenticationSystem.Web.SessionState Cookie 新增 SameSite:You can add SameSite for FormsAuthentication and System.Web.SessionState cookies by modifying the web config file:

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


實作 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:


支援 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 透過為現有的 "Authentication" 關鍵字新增新值 "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 .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 部落格中的<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 會新增飛地式 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. 在飛地式 Always Encrypted 中,用戶端可以選擇性地將加密金鑰傳送至安全飛地,也就是可視為 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. 為支援飛地式 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 類別的具象實作,以針對飛地提供者提供功能。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:

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

飛地式 Always Encrypted 的基本流程如下:The basic flow of enclave-based Always Encrypted is:

  1. 使用者會建立與 SQL Server 的 Always Encrypted 連線,以支援飛地式 Always Encrypted。The user creates an AlwaysEncrypted connection to SQL Server that supported enclave-based Always Encrypted. 驅動程式會連絡證明服務,以確保它連接到正確的飛地。The driver contacts the attestation service to ensure that it is connecting to right enclave.

  2. 一旦飛地經過證明,驅動程式就會與 SQL Server 上所裝載的安全飛地建立安全通道。Once the enclave has been attested, the driver establishes a secure channel with the secure enclave hosted on SQL Server.

  3. 在 SQL 連線期間,驅動程式會與安全飛地共用用戶端所授權的加密金鑰。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

依來源尋找 ResourceDictionaryFinding ResourceDictionaries by Source

從 .NET Framework 4.7.2 開始,診斷小幫手可以找 ResourceDictionaries 出從指定來源 Uri 建立的。Starting 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. 達成此目標的其中一個步驟,是尋找執行中的應用程式從正在編輯的字典中建立的所有 Resourcedictionary。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 to 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

此事件不會引發 (除非已 add VisualDiagnostics 啟用且已設定環境變數,否則會忽略其存取子) ENABLE_XAML_DIAGNOSTICS_SOURCE_INFOThe 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.


適用於 Windows Forms、Windows Presentation Foundation (WPF) 和 Visual Studio Tools for Office (VSTO) 的 HDPI 感知應用程式都可以使用 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:

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

如果是 Windows Forms 應用程式,不再需要執行之前的因應措施 (於應用程式組態檔而不是應用程式資訊清單中設定 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 .NET Framework.

基底類別Base classes

針對 .NET Standard 2.0 的支援Support for .NET Standard 2.0

.NET Standard 定義一組必須在每個 .NET 實作上提供的 API,而 .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 Standard 支援檔案時,這些 .NET Framework 版本才支援 .NET Standard 2.0。如需詳細資訊,請參閱 ) 4.7.1 執行時間和編譯器功能 的 blog 文章中的「BCL-.NET Standard 2.0 支援」。(Note that these versions of .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 和組態功能部落格文章中的<組態產生器>一節。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. 如需詳細資訊,請參閱新增協助程式方法來描述執行階段所支援的功能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 和其相關聯泛型型別會標示為 Serializable,以允許二進位序列化。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 執行階段和編譯器功能部落格文章中的<編譯器 - ValueTuple 可序列化>。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 執行階段和編譯器功能部落格文章中的<編譯器 - 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).

Common Language Runtime (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 執行階段和編譯器功能部落格文章中的<執行階段 -- GC 效能改善>。For more information, see the "Runtime -- GC Performance Improvements" section in the .NET Framework 4.7.1 Runtime and Compiler Features blog post.


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. 實際使用的這個值取決於 MSMQ,因為 Message 執行個體本身不會進行任何雜湊處理,而只會將值傳入 MSMQ。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 和組態功能部落格文章中的<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.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 選擇性地只會讓 HttpContext 流動。Instead, 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 和組態功能部落格文章中的<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 和組態功能部落格文章中的<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:

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

.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 blog 中的 宣佈 .NET Framework 4.7For more information, see Announcing .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 Factory 方法輕鬆建立。.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.

您可以在 GitHub 上看到 .NET Framework 4.7 密碼編譯增強功能的範例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 class 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 .NET Framework. 如需詳細資訊,請參閱 應用程式相容性 一節。For more information, see the Application compatibility section.


.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.


在 .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 中的預設記憶體監視器會在應用程式執行到接近針對處理序所設定的私用位元組上限時,或在電腦可用的總實體 RAM 不足時,通知應用程式。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.2Ability 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 TLS 1.1 or TLS 1.2 in addition to SSL 3.0 and TLS 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:

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

改進 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 FormsWindows Forms

在 .NET Framework 4.7 中,Windows Forms 改善對高 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 Forms 應用程式的高 DPI 與動態 DPI 支援。Starting with applications that target .NET Framework 4.7, .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. 如需有關如何將高 DPI 支援和動態 DPI 支援加入至 Windows Forms 應用程式的詳細資訊,請參閱 Windows Forms 中的高 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 Services Platform (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 .NET Framework. 如需詳細資訊,請參閱 應用程式相容性 一節。For more information, see the Application compatibility section.

新的 WPF 列印 API 實作New implementation for WPF printing APIs

WPF 在 System.Printing.PrintQueue 類別中的列印 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. 如需這項變更對應用程式相容性的影響,請參閱 應用程式相容性 一節。For the impact of this change on application compatibility, see the Application compatibility section.

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

.NET Framework 4.6.2 包含下列領域的新功能:.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 blog 中的 宣佈 .NET Framework 4.6.2For more information, see Announcing .NET Framework 4.6.2 in the .NET blog.


在 .NET Framework 4.6.2 中,ASP.NET 包含下列增強功能:In .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 .NET Framework 4.6.2, ASP.NET makes it easy to localize error messages. 錯誤訊息將會當地語系化,如果︰Error messages will be localized if:

  1. ValidationAttribute.ErrorMessage 提供在驗證屬性中。The ValidationAttribute.ErrorMessage is provided in the validation attribute.

  2. 資源檔儲存在 App_LocalResources 資料夾中。The resource file is stored in the App_LocalResources folder.

  3. 當地語系化資源檔的名稱具有表單 DataAnnotation.Localization.{ 名稱 }.resx ,其中 namelanguageCode - country/地區碼languageCode 格式的文化特性名稱。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:

名稱Name Value
The rating must be between 1 and 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 .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 .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 .NET Framework.

若要了解從 Unicode 6.0 到 Unicode 7.0 的字元類別變更,請參閱 Unicode 協會網站上的 The Unicode Standard, Version 7.0.0 (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 協會網站上的 The Unicode Standard, Version 8.0.0 (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.


支援包含 FIPS 186-3 DSA 的 X509 憑證Support for X509 certificates containing FIPS 186-3 DSA

.NET Framework 4.6.2 新增了對 DSA (數位簽章演算法) X509 憑證的支援,其金鑰超過 FIPS 186-2 1024 位的限制。.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, .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 .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 .NET Framework 4.6.2 made it possible for developers to make use of this feature. 由於金鑰名稱和金鑰提供者的概念是因實作而定,使用此功能需要使用實體實作類型的建構函式,而不是慣用的 factory 方法 (例如呼叫 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 參考摘要演算法。.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 常數會公開在 SignedXmlThe 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.


SQL Server (的 .NET Framework Data Provider System.Data.SqlClient 在) 4.6.2 中包含下列新功能:.NET Framework Data Provider for SQL Server (System.Data.SqlClient) includes the following new features in .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 information, 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 select the blocking period best suited for your app. 數值包括:Values include:


對於連線到 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. 如果伺服器端點名稱結尾是下列任一項,則會被視為 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


一律啟用連線集區封鎖期間。The connection pool blocking period is always enabled.


一律停用連線集區封鎖期間。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 .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 .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 .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 .NET Framework 4.6.1 and earlier but are running on .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.


這也可以用程式設計方式,以如下的程式碼完成︰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:

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

啟用這項功能時,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://localhostFor 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:

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

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 .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.

              "{x:Static PropertyGroupDescription.CompareNamesAscending}"/>

     <SortDescription PropertyName="LastName"/>

觸控鍵盤支援Touch keyboard support

觸控鍵盤支援可讓 WPF 應用程式中的焦點追蹤,方法是在可接受文字輸入的控制項收到觸控輸入時,自動叫用並關閉 Windows 10 中的觸控鍵盤。Touch keyboard support enables focus tracking in WPF applications by automatically invoking and dismissing the touch 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 .NET Framework, WPF applications can't 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 可啟用個別監視器感知。To support the recent proliferation of high-DPI and hybrid-DPI environments for WPF apps, WPF in .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 .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 .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:

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

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

在 .NET Framework 4.6.2 中,Windows Workflow Foundation 已在下欄區域中增強:In .NET Framework 4.6.2, Windows Workflow Foundation has been enhanced in the following area:

重新裝載 WF 設計工具中的 c # 運算式和 IntelliSense 支援Support for C# expressions and IntelliSense in the Rehosted WF Designer

從 .NET Framework 4.5 開始,WF 在 Visual Studio 設計工具和程式碼工作流程中都支援 c # 運算式。Starting with .NET Framework 4.5, WF supports C# expressions in both the Visual Studio Designer and in code workflows. 重新裝載工作流程設計工具是 WF 的主要功能,可讓工作流程設計工具在 Visual Studio (的應用程式中,例如 WPF) 。The Rehosted 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 Rehosted 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 在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 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 可供使用。.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 合規性模式的電腦,現在可以順利執行工作流程 V1 樣式的應用程式,並開啟工作流程追蹤。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 Platform 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.


ClickOnce 已更新為除了已經支援的 TLS 1.0 通訊協定之外,還支援 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 Forms 和 WPF 應用程式轉換成 UWP 應用程式Converting Windows Forms and WPF apps to UWP apps

Windows 現在提供將現有 Windows 傳統型應用程式 (包括 WPF 和 Windows Forms 應用程式) 移植到通用 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. 當所有的功能都移至應用程式容器處理序時,便可以移除完全信任處理序,新的 UWP 應用程式也可以供所有 Windows 10 裝置使用。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

受管理的調試 程式開發介面已在 .NET Framework 4.6.2 中增強,以在擲回時執行額外的分析,讓您可以 NullReferenceException 判斷單行原始程式碼中的哪一個變數是 nullThe unmanaged debugging API has been enhanced in .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 已加入 Unmanaged 偵錯 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 包含下列領域的新功能:.NET Framework 4.6.1 includes new features in the following areas:

如需 .NET Framework 4.6.1 的詳細資訊,請參閱下列主題:For more information on .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 憑證的支援。.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 .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.NET:The following have been added to ADO.NET:

硬體保護金鑰的「一律加密」支援Always Encrypted support for hardware protected keys

ADO.NET 現在支援在硬體安全模組 (HSM) 中以原生方式儲存 Always Encrypted 資料行主要金鑰。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 之資料行主要金鑰保護的 Always Encrypted 資料。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.

改進 MultiSubnetFailover AlwaysOn 的連接行為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. 如需 AlwaysOn 可用性群組的 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 .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

Windows 8.1 和更新版本已更新了 WPF 的拼字檢查程式,運用作業系統支援其他語言的拼字檢查。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 可以依下列順序尋找資訊來偵測控制項 tnsnames.ora 區塊的語言:As in previous versions of .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 blog 文章For more 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.


Microsoft/WPF-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. 使用 PromoterType 屬性可取得交易升級程式的 GuidThe 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.


非受控分析 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 方法來支援在載入模組之後編輯中繼資料的子集(特別是藉由加入新的、、、 AssemblyRefTypeRef TypeSpec MemberRef MemberSpecUserString 記錄),藉此提升部分限制。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.

原生映像產生器 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 .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 .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 和網頁已整合成單一架構,稱為 MVC 6。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

    • 能執行非同步回應排清的工作型 APITask-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-returning 方法Model binding supports task-returning methods

      在 .NET Framework 4.5 中,ASP.NET 新增了模型系結功能,可讓您在 Web Form 頁面和使用者控制項中以 CRUD 為基礎的資料作業,啟用可延伸、以程式碼為主的方法。In .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傳回的模型繫結方法。The Model Binding system now supports Task-returning model binding methods. 此功能可讓 Web Forms 開發人員在使用包括 Entity Framework 的較新版 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.

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

      在應用程式中,目標 .NET Framework 4.6,預設為 trueOn apps the target .NET Framework 4.6, it defaults to true. 在 .NET Framework 4.6 (以舊版 .NET Framework 為目標)上執行的應用程式,預設為此版本 falseOn apps running on .NET Framework 4.6 that target an earlier version of .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 中,HTTP/2 支援已加入 ASP.NET。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 上執行才能搭配 ASP.NET 使用 HTTP/2。You must be running on Windows 10 to use HTTP/2 with ASP.NET.

      HTTP/2 也支援使用 System.Net.Http.HttpClient API 的 Windows 10 通用平台 (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 功能的方式,已將含有 PushPromise(String)PushPromise(String, String, NameValueCollection) 這兩個多載的新方法新增到 HttpResponse 類別。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.

      瀏覽器和網頁伺服器 (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 (for example, 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.

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

    ADO.NET 現在支援 SQL Server 2016 Community Technology Preview 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. 永遠加密可保護客戶資料,所以 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).

  • Managed 程式碼的 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. 在 .NET Framework 4.6 之上執行的 64 位元處理序即會啟用全新的 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.

    新的 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. 此變更會減少虛擬記憶體,這對大型的 32 位元應用程式 (例如 Visual Studio) 特別有幫助,也可節省實體記憶體。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:

      • 一組適用於 System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPublicKey(System.Security.Cryptography.X509Certificates.X509Certificate2)System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(System.Security.Cryptography.X509Certificates.X509Certificate2) X509 憑證的擴充方法,其會在可能時傳回以 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 .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 時間來回轉換: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 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
          // 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
          ' 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.switchname

      • 參數.程式庫.參數名稱Switch.library.switchname

    • 以工作為基礎的非同步模式 (TAP) 的變更Changes to the task-based asynchronous pattern (TAP)

      若是以 .NET Framework 4.6 為目標的應用程式, Task Task<TResult> 則物件會繼承呼叫執行緒的文化特性和 UI 文化特性。For apps that target .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 .NET Framework, or that do not target a specific version of .NET Framework, is unaffected. 如需詳細資訊,請參閱 CultureInfo 類別主題的<文化特性和以工作為基礎的非同步作業>一節。For more information, see the "Culture and task-based asynchronous operations" section of the CultureInfo class topic.

      若某環境資料是指定之非同步控制流程的本機環境資料,例如 async 方法,則可用 System.Threading.AsyncLocal<T> 類別來表示。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.

      以工作為基礎的非同步模式 (TAP) 中已加入 Task.CompletedTaskTask.FromCanceledTask.FromException 三種便利的方法,可傳回特定狀態中已完成的工作。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

        可讓開始與結束事件使用識別碼來標記它們之間的事件,以代表目前作用中的所有活動。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

      WPF 中的 HDPI 支援現在更適合 .NET Framework 4.6。HDPI support in WPF is now better in .NET Framework 4.6. 已變更版面配置進位,以減少含邊界之控制項中的裁剪執行個體。Changes have been made to layout rounding to reduce instances of clipping in controls with borders. 依預設,只有當您 TargetFrameworkAttribute 的設定為 .NET Framework 4.6 時,才會啟用這項功能。By default, this feature is enabled only if your TargetFrameworkAttribute is set to .NET Framework 4.6. 以舊版 framework 為目標但在 .NET Framework 4.6 上執行的應用程式,可以藉由將下列這一行新增至 app.config 檔的區段,以加入宣告新的行為 <runtime>Applications that target earlier versions of the framework but are running on .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:


      含不同 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

      客戶在 Connect 上報告觸控產生無法預測的行為,已在 .NET Framework 4.6 中解決。Customer reports on Connect that touch produces unpredictable behavior have been addressed in .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 .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 現在還支援 TLS 1.1 和 TLS 1.2 的 SSL 版。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.

            <security mode= "None|Transport|Message|TransportWithMessageCredential" >
                <transport clientCredentialType="None|Windows|Certificate"
    • 使用不同的 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:

            <add key="wcf:httpTransportBinding:useUniqueConnectionPoolPerFactory" value="true" />
  • 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. 「非通訊協定」書籤是指與未處理的 Receive 活動無關的書籤。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. 這些活動包括 State 和 Pick。These include State and Pick. 因此如果您有使用狀態機器或包含 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 來啟用埠重複使用,如此可有效地移除並行連線的 64 KB 限制:In .NET Framework 4.6, two APIs have been added to enable port reuse, which effectively removes the 64 KB limit on concurrent connections:

      除非 HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 登錄機碼的 HWRPortReuseOnSocketBind 值設定為 0x1,否則 ServicePointManager.ReusePort 屬性皆預設為 falseBy 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.

    • 支援國際網域名稱和 PunyCodeSupport for international domain names and PunyCode

      Uri 類別中已加入新屬性 IdnHost,可更妥善支援國際化網域名稱和 PunyCode。A new property, IdnHost, has been added to the Uri class to better support international domain names and PunyCode.

  • 調整 Windows Forms 控制項的大小。Resizing in Windows Forms controls.

    此功能在 .NET Framework 4.6 中已擴充以包含 DomainUpDownNumericUpDownDataGridViewComboBoxColumnDataGridViewColumnToolStripSplitButton 型別,而且當繪製 UITypeEditor 時會使用由 Bounds 屬性所指定的矩形。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:

        <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
  • 字碼頁編碼方式的支援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 應用程式,現在可以利用將應用程式編譯成機器碼的新技術,而不是使用 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. 如需 .NET Native 概觀,請參閱 .NET Native 和編譯,其中探討 .NET Native 與 JIT 編譯和 NGEN 之間的差異,以及對您的程式碼所代表的意義。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 應用程式進行偵錯,Unmanaged 偵錯 API 已新增許多介面和列舉。To support debugging .NET Native apps, a number of new interfaces and enumerations have been added to the unmanaged debugging API. 如需詳細資訊,請參閱偵錯 (Unmanaged 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 現在可在 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 上的 .netTo access the code, see .NET on GitHub. 如需詳細資訊以及如何參與這些封裝,請參閱GitHub 上.net 簡介 .net首頁。For more information and how to contribute to these packages, see Introduction to .NET, .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 Forms 的增強功能包括:Improvements to Windows Forms include:

  • 調整 Windows Forms 控制項的大小。Resizing in Windows Forms controls. 您可以透過在應用程式的應用程式組態檔中選擇加入一個項目,使用系統 DPI 設定來調整控制項的元件大小 (例如屬性方格中出現的圖示)。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 Forms 控制項如下:This feature is currently supported in the following Windows Forms controls:

    若要啟用這項功能,請將新的專案新增 <appSettings> 至設定檔 ( # A0) ,然後將 EnableWindowsFormsHighDpiAutoResizing 元素設定為 trueTo enable this feature, add a new <appSettings> element to the configuration file (app.config) and set the EnableWindowsFormsHighDpiAutoResizing element to true:

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

在 Visual Studio 2013 中對您的 .NET Framework 應用程式進行偵錯時的改進功能包括:Improvements when debugging your .NET Framework apps in Visual Studio 2013 include:

  • 在 Visual Studio Debugger 中傳回值。Return values in the Visual Studio debugger. 當您在 Visual Studio 2013 中對 Managed 應用程式進行偵錯時,[自動變數] 視窗會顯示方法的傳回類型和值。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 位元 Managed 應用程式支援「編輯後繼續」功能。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 公告 (英文)的<Async-aware debugging> (非同步感知偵錯) 一節中,閱讀此功能的相關資訊。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 開始,您可以使用 Managed 特性指引最佳化工具 (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 .NET Framework 4.5, background garbage collection is automatically enabled. 請參閱記憶體回收的基本概念主題的<背景伺服器記憶體回收>一節。See the Background Server Garbage Collection section of the Fundamentals of Garbage Collection topic.

  • 背景 Just-in-Time (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 上使用類別時,在應用程式中支援2008版的國際化功能變數名稱 (IDNA) 標準 System.Globalization.IdnMappingSupport 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. 請參閱適用於 Windows 市集應用程式之 .NET Framework 中的反映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 .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 Gallery 取得這個子集的可下載套件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 .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.


在 .NET Framework 4.5 中, ( # A0) 的資源檔產生器可讓您建立 .resw 檔案,以從內嵌于 .NET Framework 元件的 .resources 檔案,在 Windows 8. x Store 應用程式中使用。In .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).

Managed 特性指引最佳化 (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 (Managed 特性指引最佳化工具)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 針對平行計算提供了數個新功能和增強功能。.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 blog 進行平行程式設計中, .NET Framework 4.5 中的平行處理原則的新專案。See the entry What's New for Parallelism in .NET Framework 4.5 in the Parallel Programming with .NET blog.


ASP.NET 4.5 和 4.5.1 加入了 Web Forms、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:


.NET Framework 4.5 為 HTTP 應用程式提供新的程式設計介面。.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.

另外還包括對新的程式設計介面的支援,可使用現有的 HttpListener 和相關類別接受 WebSocket 連接並進行互動。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, .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.MailFor more information, see the System.Net.Mail namespace.

  • 改進的 IPv6 支援。Improved IPv6 support. 如需詳細資訊,請參閱 System.Net.NetworkInformationFor 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 .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)

在 .NET Framework 4.5 中,已新增下列功能,可讓您更輕鬆地撰寫和維護 WCF) 應用程式 Windows Communication Foundation (:In .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.

  • Websocket 支援,可透過與 TCP 傳輸類似的效能特性在連接埠 80 與 443 之間進行真正的雙向通訊。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 傳輸,可讓開發人員撰寫使用「射後不理」(Fire and Forget) 傳訊功能的服務。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 .NET Framework 4.5, several new features were added to Windows Workflow Foundation (WF), including:

  • 狀態機器工作流程,最初是在 .NET Framework 4.0.1 中引進 (.NET Framework 4 Platform Update 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 .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) 工作流程服務,可提供自動配合現有服務合約產生活動的支援。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 .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 平台上執行的 Managed 組件。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 和 .NET,以) 目標的 Windows 8 x 商店應用程式。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