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

工具Tooling

.NET Core 2.1 SDK (v 2.1.300),该工具与 .NET Core 2.1 一起提供,包括以下更改和增强功能: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 进程的参数直接传递到 dotnet watch 命令的选项。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 Core3.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 命令,例如 runWhen 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 (v 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 (v 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"
    
  • 若要在每个项目的基础上使用分层编译,将 <TieredCompilation> 属性添加到 MSBuild 项目文件的 <PropertyGroup> 部分,如以下示例所示: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 浏览器和主 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后者依赖于本机实现),或者通过将类实例传递到 HttpClient 构造函数来使用 SocketsHttpHandler 类。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 实现,则需要部署 libcurlOn 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