.NET Core 2.1 的新功能What's new in .NET Core 2.1

.NET Core 2.1 包含針對下列區域的增強與新功能:.NET Core 2.1 includes enhancements and new features in the following areas:

ToolingTooling

隨附於 .NET Core 2.1 的工具 .NET Core 2.1 SDK (2.1.300 版) 包含下列變更與增強功能:The .NET Core 2.1 SDK (v 2.1.300), the tooling included with .NET Core 2.1, includes the following changes and enhancements:

建置效能改進Build performance improvements

.NET Core 2.1 的主要重點在於改進建置時間效能,特別是針對累加建置。A major focus of .NET Core 2.1 is improving build-time performance, particularly for incremental builds. 這些效能改進適用於使用 dotnet build 的命令列建置和 Visual Studio 中的建置。These performance improvements apply to both command-line builds using dotnet build and to builds in Visual Studio. 改進的一些個別區域包含:Some individual areas of improvement include:

  • 針對套件資產解析,僅解析組建所使用的資產,而非所有資產。For package asset resolution, resolving only assets used by a build rather than all assets.

  • 組件參考的快取。Caching of assembly references.

  • 使用長時間執行的 SDK 組建伺服器,這些是跨越個別 dotnet build 引動過程的處理序。Use of long-running SDK build servers, which are processes that span across individual dotnet build invocations. 它們消除了每次執行 dotnet build 時,需要以 JIT 編譯大型程式碼區塊的需求。They eliminate the need to JIT-compile large blocks of code every time dotnet build is run. 組建伺服器處理序可使用下列命令自動終止:Build server processes can be automatically terminated with the following command:

    dotnet buildserver shutdown
    

新的 CLI 命令New CLI commands

先前僅能透過 DotnetCliToolReference 於個別專案上使用的數個工具,現在皆已做為 .NET Core SDK 的一部分提供。A number of tools that were available only on a per project basis using DotnetCliToolReference are now available as part of the .NET Core SDK. 這些工具包括:These tools include:

  • dotnet watch 提供檔案系統監看員,能先等候檔案變更再執行一組指定的命令。dotnet watch provides a file system watcher that waits for a file to change before executing a designated set of commands. 例如,下列命令會自動重建目前的專案,並在其中的檔案發生變更時產生詳細資訊輸出:For example, the following command automatically rebuilds the current project and generates verbose output whenever a file in it changes:

    dotnet watch -- --verbose build
    

    請注意到位於 --verbose 選項之前的 -- 選項。Note the -- option that precedes the --verbose option. 它能將直接傳遞給 dotnet watch 命令的選項,與傳遞給子 dotnet 處理序的引數分隔開來。It delimits the options passed directly to the dotnet watch command from the arguments that are passed to the child dotnet process. 如果沒有它的話,--verbose 選項將會套用至 dotnet watch 命令,而非 dotnet build 命令。Without it, the --verbose option applies to the dotnet watch command, not the dotnet build command.

    如需詳細資訊,請參閱使用 dotnet watch 開發 ASP.NET Core 應用程式For more information, see Develop ASP.NET Core apps using dotnet watch

  • dotnet dev-certs 能產生和管理在開發 ASP.NET Core 應用程式期間使用的憑證。dotnet dev-certs generates and manages certificates used during development in ASP.NET Core applications.

  • dotnet user-secrets 能管理 ASP.NET Core 中使用者祕密存放區中的祕密。dotnet user-secrets manages the secrets in a user secret store in ASP.NET Core applications.

  • dotnet sql-cache 能在 Microsoft SQL Server 資料庫中建立資料表和索引以用於分散式快取。dotnet sql-cache creates a table and indexes in a Microsoft SQL Server database to be used for distributed caching.

  • dotnet ef 是用來管理 Entity Framework Core 應用程式中資料庫、DbContext 物件和移轉作業的工具。dotnet ef is a tool for managing databases, DbContext objects, and migrations in Entity Framework Core applications. 如需詳細資訊,請參閱 EF Core .NET 命令列工具For more information, see EF Core .NET Command-line Tools.

通用工具Global Tools

.NET Core 2.1 支援通用工具,亦即從命令列以通用方式提供的自訂工具。.NET Core 2.1 supports Global Tools -- that is, custom tools that are available globally from the command line. 舊版 .NET Core 的擴充性模型,只能透過使用 DotnetCliToolReference 來使自訂工具可供每個專案使用。The extensibility model in previous versions of .NET Core made custom tools available on a per project basis only by using DotnetCliToolReference.

若要安裝通用工具,您需使用 dotnet tool install 命令。To install a Global Tool, you use the dotnet tool install command. 例如:For example:

dotnet tool install -g dotnetsay

安裝之後,您就可在命令列中指定工具名稱來執行該工具。Once installed, the tool can be run from the command line by specifying the tool name. 如需詳細資訊,請參閱 .NET Core 通用工具概觀For more information, see .NET Core Global Tools overview.

使用 dotnet tool 命令來管理工具Tool management with the dotnet tool command

在 .NET Core 2.1 SDK 中,所有工具作業都使用 dotnet tool 命令。In .NET Core 2.1 SDK, all tools operations use the dotnet tool command. 有下列選項可供使用:The following options are available:

向前復原Roll forward

從 .NET Core 2.0 開始,所有 .NET Core 應用程式都會自動向前復原為系統上安裝的最新次要版本。All .NET Core applications starting with .NET Core 2.0 automatically roll forward to the latest minor version installed on a system.

從 .NET Core 2.0 開始,如果用來建置應用程式的 .NET Core 版本不存在於執行階段中,則應用程式會自動針對已安裝的最新 .NET Core 次要版本執行。Starting with .NET Core 2.0, if the version of .NET Core that an application was built with is not present at runtime, the application automatically runs against the latest installed minor version of .NET Core. 換句話說,如果應用程式是使用 .NET Core 2.0 建置,而主機系統上不存在 .NET Core 2.0,但是有 .NET Core 2.1,則該應用程式會搭配 NET Core 2.1 執行。In other words, if an application is built with .NET Core 2.0, and .NET Core 2.0 is not present on the host system but .NET Core 2.1 is, the application runs with .NET Core 2.1.

重要

此向前復原行為不適用於預覽版本。This roll-forward behavior doesn't apply to preview releases. 根據預設,也不會套用至主要版本,但可透過以下設定進行變更。By default, it also doesn't apply to major releases, but this can be changed with the settings below.

您可以透過變更無候選版共用架構的向前復原設定,來修改此行為。You can modify this behavior by changing the setting for the roll-forward on no candidate shared framework. 可用的設定為:The available settings are:

  • 0 - 停用次要版本向前復原行為。0 - disable minor version roll-forward behavior. 使用此設定,為 .NET Core 2.0.0 建置的應用程式會向前復原為 .NET Core 2.0.1,而不是 .NET Core 2.2.0 或 .NET Core 3.0.0。With this setting, an application built for .NET Core 2.0.0 will roll forward to .NET Core 2.0.1, but not to .NET Core 2.2.0 or .NET Core 3.0.0.
  • 1 - 啟用次要版本向前復原行為。1 - enable minor version roll-forward behavior. 這是設定的預設值。This is the default value for the setting. 使用此設定,為 .NET Core 2.0.0 建置的應用程式會依安裝的版本向前復原為 .NET Core 2.0.1 或 NET Core 2.2.0,但不會是 .NET Core 3.0.0。With this setting, an application built for .NET Core 2.0.0 will roll forward to either .NET Core 2.0.1 or .NET Core 2.2.0, depending on which one is installed, but it will not roll forward to .NET Core 3.0.0.
  • 2 - 啟用次要與主要版本的向前復原行為。2 - enable minor and major version roll-forward behavior. 若已設定,那麼即使是其他主要版本也會列入考量,因此為 .NET Core 2.0.0 建置的應用程式會向前復原為 .NET Core 3.0.0。If set, even different major versions are considered, so an application built for .NET Core 2.0.0 will roll forward to .NET Core 3.0.0.

您可用以下三種方式的任一種修改此設定:You can modify this setting in any of three ways:

  • DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX 環境變數設定為所需的值。Set the DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX environment variable to the desired value.

  • 將下列這一行新增至 runtimeconfig.json 檔案,並使用所需的值:Add the following line with the desired value to the runtimeconfig.json file:

    "rollForwardOnNoCandidateFx" : 0
    
  • 在使用 .NET Core CLI 工具時,將以下選項新增至 .NET Core 命令 (例如 run),並使用所需的值:When using .NET Core CLI tools, add the following option with the desired value to a .NET Core command such as run:

    dotnet run --rollForwardOnNoCandidateFx=0
    

修補版本向前復原與此設定無關,而且如有任何次要或主要版本向前復原,在套用之後就會完成。Patch version roll forward is independent of this setting and is done after any potential minor or major version roll forward is applied.

部署Deployment

獨立的應用程式服務Self-contained application servicing

dotnet publish 現在會搭配服務執行階段版本發佈獨立應用程式。dotnet publish now publishes self-contained applications with a serviced runtime version. 當您搭配 .NET Core 2.1 SDK (2.1.300 版) 發佈獨立應用程式時,應用程式就會包含該 SDK 已知的最新服務執行階段版本。When you publish a self-contained application with the .NET Core 2.1 SDK (v 2.1.300), your application includes the latest serviced runtime version known by that SDK. 當您升級至最新的 SDK 時,將會搭配最新的 .NET Core 執行階段版本一起發佈。When you upgrade to the latest SDK, you’ll publish with the latest .NET Core runtime version. 這適用於 .NET Core 1.0 執行階段和更新版本。This applies for .NET Core 1.0 runtimes and later.

獨立發佈會仰賴 NuGet.org 上的執行階段版本。您的電腦上不需要有服務執行階段。Self-contained publishing relies on runtime versions on NuGet.org. You do not need to have the serviced runtime on your machine.

使用 .NET Core 2.0 SDK 時,獨立應用程式會搭配 .NET Core 2.0.0 執行階段一起發佈,除非有透過 RuntimeFrameworkVersion 屬性指定其他版本。Using the .NET Core 2.0 SDK, self-contained applications are published with the .NET Core 2.0.0 runtime unless a different version is specified via the RuntimeFrameworkVersion property. 藉由這項新行為,您將不再需要設定此屬性來為獨立應用程式選取較新的執行階段版本。With this new behavior, you’ll no longer need to set this property to select a higher runtime version for a self-contained application. 從現在起,最簡單的方法將會是一律搭配 .NET Core 2.1 SDK (2.1.300 版) 發佈。The easiest approach going forward is to always publish with .NET Core 2.1 SDK (v 2.1.300).

如需詳細資訊,請參閱獨立式部署執行階段向前復原For more information, see Self-contained deployment runtime roll forward.

Windows 相容性套件Windows Compatibility Pack

當您從 .NET Framework 將現有的程式碼移植到 .NET Core 時,可以使用 Windows 相容性套件 (英文)。When you port existing code from the .NET Framework to .NET Core, you can use the Windows Compatibility Pack. 與 .NET Core 所提供 API 相比,它還額外提供超過 20,000 個 API。It provides access to 20,000 more APIs than are available in .NET Core. 這些 API 包括 System.Drawing 命名空間中的類型、EventLog 類別、WMI、效能計數器、Windows 服務,以及Windows 登錄類型和成員。These APIs include types in the System.Drawing namespace, the EventLog class, WMI, Performance Counters, Windows Services, and the Windows registry types and members.

JIT 編譯器的改進項目JIT compiler improvements

.NET Core 併入新的 JIT 編譯器技術,稱為「階層式編譯」(也稱為「調適型最佳化」),可大幅地提升效能。.NET Core incorporates a new JIT compiler technology called tiered compilation (also known as adaptive optimization) that can significantly improve performance. 階層式編譯是可選擇加入的設定。Tiered compilation is an opt-in setting.

由 JIT 編譯器所執行的其中一個重要工作,是將程式碼的執行最佳化。One of the important tasks performed by the JIT compiler is optimizing code execution. 不過,針對很少使用的程式碼路徑,編譯器將程式碼最佳化的時間,可能會比執行階段執行未最佳化程式碼的時間還要久。For little-used code paths, however, the compiler may spend more time optimizing code than the runtime spends running unoptimized code. 階層式編譯會在 JIT 編譯中引入兩個階段:Tiered compilation introduces two stages in JIT compilation:

  • 第一層:盡快產生程式碼。A first tier, which generates code as quickly as possible.

  • 第二層:針對那些經常執行的方法產生最佳化的程式碼。A second tier, which generates optimized code for those methods that are executed frequently. 編譯的第二層會以平行方式執行以增強效能。The second tier of compilation is performed in parallel for enhanced performance.

您能以兩種方式選擇加入階層式編譯。You can opt into tiered compilation in either of two ways.

  • 若要在使用 .NET Core 2.1 SDK 的所有專案中使用階層式編譯,請設定下列環境變數:To use tiered compilation in all projects that use the .NET Core 2.1 SDK, set the following environment variable:

    COMPlus_TieredCompilation="1"
    
  • 若要針對個別專案使用階層式編譯,請在 MSBuild 專案檔的 <PropertyGroup> 區段中加入 <TieredCompilation> 屬性,如下列範例所示:To use tiered compilation on a per-project basis, add the <TieredCompilation> property to the <PropertyGroup> section of the MSBuild project file, as the following example shows:

    <PropertyGroup>
        <!-- other property definitions -->
    
        <TieredCompilation>true</TieredCompilation>
    </PropertyGroup>
    

API 變更API changes

Span<T>Memory<T>Span<T> and Memory<T>

.NET core 2.1 包含一些新的類型,可讓處理陣列和其他記憶體類型變得更有效率。.NET Core 2.1 includes some new types that make working with arrays and other types of memory much more efficient. 新的類型包括:The new types include:

沒有這些類型的話,當您傳遞項目作為陣列的一部份或記憶體緩衝區的某個區段時,必須先複製該資料的某些部分,然後才能將它傳遞給方法。Without these types, when passing such items as a portion of an array or a section of a memory buffer, you have to make a copy of some portion of the data before passing it to a method. 這些類型能提供該資料的虛擬檢視,以免除額外配置記憶體和複製作業的需求。These types provide a virtual view of that data that eliminates the need for the additional memory allocation and copy operations.

下列範例使用 Span<T>Memory<T> 執行個體來提供陣列中 10 個元素的虛擬檢視。The following example uses a Span<T> and Memory<T> instance to provide a virtual view of 10 elements of an array.

using System;

class Program
{
    static void Main()
    {
        int[] numbers = new int[100];
        for (int i = 0; i < 100; i++)
        {
            numbers[i] = i * 2;
        }

        var part = new Span<int>(numbers, start: 10, length: 10);
        foreach (var value in part)
            Console.Write($"{value}  ");
    }
}
// The example displays the following output:
//     20  22  24  26  28  30  32  34  36  38
Module Program
    Sub Main()
        Dim numbers As Integer() = New Integer(99) {}

        For i As Integer = 0 To 99
            numbers(i) = i * 2
        Next

        Dim part = New Memory(Of Integer)(numbers, start:=10, length:=10)

        For Each value In part.Span
            Console.Write($"{value}  ")
        Next
    End Sub
End Module
' The example displays the following output:
'     20  22  24  26  28  30  32  34  36  38

Brotli 壓縮Brotli compression

.NET Core 2.1 新增對 Brotli 壓縮和解壓縮的支援。.NET Core 2.1 adds support for Brotli compression and decompression. Brotli 是定義於 RFC 7932 (英文) 中的一般用途無失真壓縮演算法,並受到大部分網頁瀏覽器和主流 Web 伺服器的支援。Brotli is a general-purpose lossless compression algorithm that is defined in RFC 7932 and is supported by most web browsers and major web servers. 您可以使用資料流形式的 System.IO.Compression.BrotliStream 類別,或是高效能範圍型的 System.IO.Compression.BrotliEncoderSystem.IO.Compression.BrotliDecoder 類別。You can use the stream-based System.IO.Compression.BrotliStream class or the high-performance span-based System.IO.Compression.BrotliEncoder and System.IO.Compression.BrotliDecoder classes. 下列範例說明搭配 BrotliStream 類別進行壓縮:The following example illustrates compression with the BrotliStream class:

public static Stream DecompressWithBrotli(Stream toDecompress)   
{
    MemoryStream decompressedStream = new MemoryStream();
    using (BrotliStream decompressionStream = new BrotliStream(toDecompress, CompressionMode.Decompress))
    {
        decompressionStream.CopyTo(decompressedStream);
    }
    decompressedStream.Position = 0;
    return decompressedStream;
}

BrotliStream 行為與 DeflateStreamGZipStream 相同,這可讓您輕鬆地將呼叫這些 API 的程式碼轉換為 BrotliStreamThe BrotliStream behavior is the same as DeflateStream and GZipStream, which makes it easy to convert code that calls these APIs to BrotliStream.

新的密碼編譯 API 和密碼編譯改進功能New cryptography APIs and cryptography improvements

.NET Core 2.1 包含許多針對密碼編譯 API 的增強功能:.NET Core 2.1 includes numerous enhancements to the cryptography APIs:

通訊端增強功能Sockets improvements

.NET Core 包含新的類型 System.Net.Http.SocketsHttpHandler,以及重新撰寫的 System.Net.Http.HttpMessageHandler,來形成較高層級網路 API 的基礎。.NET Core includes a new type, System.Net.Http.SocketsHttpHandler, and a rewritten System.Net.Http.HttpMessageHandler, that form the basis of higher-level networking APIs. 舉例來說,System.Net.Http.SocketsHttpHandlerHttpClient 實作的基礎。System.Net.Http.SocketsHttpHandler, for example, is the basis of the HttpClient implementation. 在舊版的 .NET Core 當中,較高層級的 API 是以原生網路實作為基礎。In previous versions of .NET Core, higher-level APIs were based on native networking implementations.

在 .NET Core 2.1 中導入的通訊端實作有一些優點:The sockets implementation introduced in .NET Core 2.1 has a number of advantages:

  • 與之前的實作相比,能提供顯著的效能提升。A significant performance improvement when compared with the previous implementation.

  • 消除平台相依性,並進一步簡化部署和維護作業。Elimination of platform dependencies, which simplifies deployment and servicing.

  • 橫跨所有 .NET Core 平台的一致行為。Consistent behavior across all .NET Core platforms.

SocketsHttpHandler 是 .NET Core 2.1 中的預設實作。SocketsHttpHandler is the default implementation in .NET Core 2.1. 不過,您可以呼叫 AppContext.SetSwitch 方法來將應用程式設定為使用舊版的 HttpClientHandler 類別:However, you can configure your application to use the older HttpClientHandler class by calling the AppContext.SetSwitch method:

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", False)

您也可以使用環境變數來選擇退出使用以 SocketsHttpHandler 為基礎的通訊端實作。You can also use an environment variable to opt out of using sockets implementations based on SocketsHttpHandler. 若要這麼做,請將 DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER 設為 false 或 0。To do this, set the DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER to either false or 0.

在 Windows 上,您也可以選擇使用依賴原生實作的 System.Net.Http.WinHttpHandler,或是將 SocketsHttpHandler 類別的執行個體傳遞到 HttpClient 建構函式來使用該類別。On Windows, you can also choose to use System.Net.Http.WinHttpHandler, which relies on a native implementation, or the SocketsHttpHandler class by passing an instance of the class to the HttpClient constructor.

在 Linux 和 macOS 上,您只能針對個別處理序設定 HttpClientOn Linux and macOS, you can only configure HttpClient on a per-process basis. 在 Linux 上,如果您要使用舊的 HttpClient 實作,便需要部署 libcurl (英文)。On Linux, you need to deploy libcurl if you want to use the old HttpClient implementation. (它會隨 .NET Core 2.0 一起安裝)(It is installed with .NET Core 2.0.)

另請參閱See also