Когда выйдет net framework 5
Обновления Visual Basic
Описание | Параметр dotnet new |
---|---|
Консольное приложение | console |
Библиотека классов | classlib |
Приложение WPF | wpf |
Библиотека классов WPF | wpflib |
Библиотека настраиваемых элементов управления WPF | wpfcustomcontrollib |
Библиотека пользовательских элементов управления WPF | wpfusercontrollib |
Приложение Windows Forms (WinForms) | winforms |
Библиотека классов для Windows Forms (WinForms) | winformslib |
Проект модульного теста | mstest |
Тестовый проект NUnit 3 | nunit |
Элемент теста NUnit 3 | nunit-test |
Тестовый проект xUnit | xunit |
Высокая производительность и продуктивность
JIT-компиляторы хорошо подходят для долго работающих облаков и клиентских сценариев. Они способны генерировать код, учитывающий особенности аппаратной конфигурации, в том числе специфические процессорные инструкции. Также JIT может заново генерировать методы во время исполнения, эта методика позволяет компилировать с высокой скоростью, в то же время создавая тонко настроенную версию кода, если какие-то методы используются часто.
Инструменты разработчиков — ещё одна сфера, в которой JIT прекрасно себя зарекомендовала, например, dotnet watch или режим “edit and continue”. Для работы инструментов часто требуется многократно компилировать и загружать код в одном и том же процессе без перезапуска, и делать это нужно очень быстро.
Microsoft.Extensions.Logging
We’ve made improvements to the console log provider in the Microsoft.Extensions.Logging library. You can now implement a custom ConsoleFormatter to exercise complete control over formatting and colorization of the console output. The formatter APIs allow for rich formatting by implementing a subset of the VT-100 (supported by most modern terminals) escape sequences. The console logger can parse out escape sequences on unsupported terminals allowing you to author a single formatter for all terminals.
In addition to support for custom formatters, we’ve also added a built-in JSON formatter that emits structured JSON logs to the console.
Closing
Event pipe
The workflow is described in the dotnet-trace docs. You can see assembly loading information for a simple test app.
System.Text.Json
If you are looking at using System.Text.Json as an alternative to Newtonsoft.Json , you should check out the migration guide. The guide clarifies the relationship between these two APIs. System.Text.Json is intended to cover many of the same scenarios as Newtonsoft.Json , but it’s not intended to be a drop-in replacement for or achieve feature parity with the popular JSON library. We try to maintain a balance between performance and usability, and bias to performance in our design choices.
The following example deserializes weather forecast JSON data into a Forecast record, using the new
You can then run the previous sample.
Быстрый запуск, низкое потребление ресурсов процессора (footprint) и уменьшение потребления памяти
Есть два типа AOT-решений:
- Требующие полной AOT-компиляции.
- Решения, большая часть кода которых AOT-скомпилирована, но всё же позволяющие использовать JIT или интерпретатор для таких паттернов кода, которые не дружат с AOT (например, дженерики).
AOT-компиляция останется необходимой для iOS, WebAssembly и некоторых игровых приставок. Мы сделаем её опциональной для приложений, которые встраиваются в технику (appliance-like), для которых требуется быстрый запуск и/или низкое потребление ресурсов процессора.
Прочее
Помимо глобальных улучшений платформы Microsoft также неплохо поработали над отдельными библиотеками.
Помимо прочего, для десктопной разработки под Windows также добавили нормальный визуальный дизайнер, тулинг, новые контролы и улучшенную поддержку для старых. Словом — если вы разрабатываете приложения с использованием WinForms или WPF, ваша жизнь станет лучше.
Еще больше улучшений появилось для фулстек веб-разработки с использованием Blazor. Главное из них это улучшения производительности — Microsoft обещают, что WebAssembly версия Blazor ускорится аж в три раза. Одной из основных причин такого роста производительности стал пререндер на стороне сервера. А еще добавили ленивую подгрузку зависимостей, изоляцию CSS/JS в рамках файла, новые контролы и многое другое. В общем, если вы собирались попробовать Blazor, но все никак не доходили руки — сейчас он выглядит куда более production-ready технологией.
А еще Microsoft выкатили Project Tye, который как раз является инструментом для удобного управления микросервисами. На текущий момент трудно сказать, стоит ли использовать Tye в продакшене, но обратить внимание и поиграться с ним в свободное время определенно нужно.
Коротко — Microsoft улучшили поддержку отдельных инструментов и добавили приятных фич для облака. Если вы используете WinForms, WPF или Blazor — обновиться определенно стоит.
Исполняющие среды
Arm64 Performance
- Tune JIT optimizations for Arm64 (example)
- Enable and take advantage of Arm64 hardware intrinsics (example).
- Adjust performance-critical algorithms in libraries for Arm64 (example).
We’re making our first big investments in Arm64 performance in 5.0, and we’ll continue this effort in subsequent releases. We work directly with engineers from Arm Holdings to prioritize product improvements and to design algorithms that best take advantage of the Armv8 ISA. Some of these improvements will accrue value to Arm32, however, we are not applying unique effort to Arm32. If you use a Raspberry Pi, you’ll enjoy these improvements if you install the new Arm64 version of Raspberry Pi OS.
Languages
Support for records
JsonSerializer support for records is almost the same as what I just showed you for immutable types. The difference I want to show here is deserializing a JSON object to a record that exposes a parameterized constructor and an optional init property.
Here’s the program, including the record definition:
It produces the following output:
Improved support for immutable types
There are multiple patterns for defining immutable types. Records are just the newest one. JsonSerializer now has support for immutable types.
In this example, you’ll see the serialization with an immutable struct.
Note: The JsonConstructor attribute is required to specify the constructor to use with structs. With classes, if there is only a single constructor, then the attribute is not required. Same with records.
It produces the following output:
Перфоманс
Помимо результатов бенчмарков от TechEmpower, Microsoft также рассказывает и о других улучшениях. Например, сериализация JSON стала работать на 20% быстрее, а сериализация больших коллекций и массивов ускорилась аж в три раза.
Другие изменения коснулись JIT компиляции, асинхронности и многих методов базовой библиотеки. Это касается методов, относящихся к работе со строками, регулярными выражениями и, что особенно важно, с коллекциями и сериализацией. Во все той же статье приводится много примеров таких изменений, с соответствующими пулл-реквестами и бенчмарками.
Изменения в JSON сериализации выглядят особенно впечатляюще. Только посмотрите на результаты бенчмарка по сериализации больших массивов!
Коротко — пятый дотнет сильно вырос в производительности и это важнейшая часть нового релиза. Большинство стандартных веб-приложений могут ожидать прирост производительности на 20% и выше, а отдельные приложения могут и вовсе ускориться в несколько раз.
Unified platform vision
Let’s switch to looking at what’s new in the 5.0 release.
Dump debugging
Миграция
Garbage Collector
The following improvements were made in the GC.
The GC now exposes detailed information of the most recent collection, via the GC.GetGCMemoryInfo method. The GCMemoryInfo struct provides information about machine memory, heap memory and the most recent collection, or most recent collection of the kind of GC you specify – ephemeral, full blocking or background GC.
The most likely use cases for using this new API are for logging/monitoring or to indicate to a loader balancer that a machine should be taken out of rotation to request a full GC. It could also be used to avoid container hard-limits by reducing the size of caches.
Another, small but impactful change, was made to defer the expensive reset memory operation to low-memory situations. We expect these changes in policy to lower the GC latency (and GC CPU usage in general).
Expanding System.DirectoryServices.Protocols to Linux and macOS
We’ve been adding cross-platform support for System.DirectoryServices.Protocols. This includes support for Linux and support for macOS. Windows support was pre-existing.
System.DirectoryServices.Protocols is a lower-level API than System.DirectoryServices, and enables (or can be used to enable) more scenarios. System.DirectoryServices includes Windows-only concepts/implementations, so it was not an obvious choice to make cross-platform. Both API-sets enable controlling and interacting with a directory service server, like LDAP or Active Directory.
Windows Arm64
Logical and property patterns
Another new pattern is property patterns. You can see several properties checks in my Mycroft information access 6.0 sample. The following code is taken from the PN532 RFID and NFC reader sample.
This code tests if pollingType (which is typed as byte[]? ) is null or contains >15 bytes.
I want to show you two more patterns. The first is a logical pattern in Mcp25xxx CAN bus.
Языковое
Самое заметное изменение — это record-типы, позволяющие избавиться от бойлерплейта при написании DTO. Записи — это иммутабельные ссылочные типы с простым и коротким объявлением. В них по умолчанию определены методы Equals, HashCode, Copy, Clone, PrintMembers и ToString — разумеется, все они используют значения полей типа для выполнения операций. То есть Equals корректно сравнивает две записи по значениям, а не по ссылке.
Также записи поддерживают синтаксис копирования с изменением значений полей через with, например:
Больше о применении записей вы можете почитать в блоге Владимира Хорикова и в публикации от Konrad Kokosa.
Другое важное изменение — это обновленный pattern matching. Теперь паттерны могут настраиваться по типам и операторам сравнения, причем несколько разных сравнений вы можете объединять через логические операторы. Например:
Остальные изменения не столь заметны — они касаются верхнеуровневых программ (возможность писать короткие программы без базового класса и функции main), упрощенного синтаксиса для new (без указания типа), init-only сеттеров и прочего.
Улучшения в Preview 1
Следующие улучшения в Preview 1:
Улучшения производительности регулярных выражений
Мы вложили значительные средства в движок Regex. Во многих протестированных нами выражениях эти улучшения обычно приводят к повышению производительности в 3-6 раз, а в некоторых случаях и к гораздо большему. В скором времени у нас будет пост в блоге, в котором эти улучшения будут описаны более подробно.
Улучшение качества кода в RyuJIT
Каждый релиз включает набор улучшений производительности для кода, который генерирует JIT. Мы называем этот тип улучшений «CQ» или качество кода. В большинстве случаев эти улучшения также применяются к коду, созданному для готовых к запуску образов.
-
– Удалите необходимость генерировать null checks в большем количестве случаев, наблюдая больше шаблонов, где null checks, вероятно, не нужны. – JIT ищет и сворачивает дублирующиеся выражения, которые нужно оценивать только один раз. – Оптимизация этого шаблона и свертывание кода до правильного целочисленного значения. – Переупорядочевание фазы в JIT, чтобы раньше можно было использовать ключевые оптимизации, что привело к лучшему качеству кода и меньшему количеству работы для следующих фаз, что увеличивает пропускную способность JIT («TP» в ссылочном PR).
Диагностика нагрузки сборки добавлена в event pipe
dotnet-trace collect --providers Microsoft-Windows-DotNETRuntime:4:4 --process-id [process ID]
Рабочий процесс описан в разделе Trace Assembly Loading with Event Pipe. Вы можете увидеть информацию о загрузке сборки для простого тестового приложения.
API для профилирования событий (Event Pipe)
Консолидация репозиториев GitHub
ASP.NET Core 5.0 основана на .NET 5, но у нее сохраняется имя "Core", чтобы избежать путаницы с ASP.NET MVC 5. Аналогичным образом у Entity Framework Core 5.0 сохраняется имя "Core", чтобы избежать путаницы с Entity Framework 5 и 6.
P95+ Latency
Preserving references in JSON object graphs
JsonSerializer has added support for preserving (circular) references within JSON object graphs. It does this by storing IDs that can be reconstituted when a JSON string is deserialized back to objects.
Records
It is then used a little later in the same file, with familiar syntax:
Improving tiered compilation performance
We’ve been working on improving tiered compilation for multiple releases. We continue to see it as a critical performance feature, for both startup and steady-state performance. We’ve made two big improvements to tiered compilation this release.
Another performance challenge we found was using tiered compilation for methods with loops. The fundamental problem is that you can have a cold method (only called once or a few times; $lt; n) with a loop that iterates many times. We call this pathological scenario “cold method; hot loop”. It is easy to imagine this happening with the Main method of an application. As a result, we disabled tiered compilation for methods with loops by default. Instead, we enabled applications to opt into using tiered compilation with loops. PowerShell is an application that chose to do this, after seeing high single-digit performance improvements in some scenarios.
To address methods with loops better, we implemented on-stack replacement (OSR). This is similar to a feature that the Java Virtual Machines has, of the same name. OSR enables code executed by a currently running method to be re-compiled in the middle of method execution, while those methods are active “on-stack”. This feature is currently experimental and opt-in, and on x64 only.
To use OSR, multiple features must be enabled. The PowerShell project file is a good starting point. You will notice that tiered compilation and all quick-jit features are enabled. In addition, you need to set the COMPlus_TC_OnStackReplacement environment variable to 1 .
Alternatively, you can set the following two environment variables, assuming all other settings have their default values:
- COMPlus_TC_QuickJitForLoops=1
- COMPlus_TC_OnStackReplacement=1
ClickOnce
We had two goals from the start of the project:
- Enable a familiar experience for ClickOnce in Visual Studio.
- Enable a modern CI/CD for ClickOnce publishing with command-line flows, with either MSBuild or the Mage tool.
It’s easiest to show you the experience in pictures.
Let’s start with the Visual Studio experience, which is centered around project publishing.
You might wonder if you can still be able to take advantage of ClickOnce offline and updating features. Yes, you can.
The Mage installation command follows:
After you’ve produced and distributed your ClickOnce installer, your users will see the familiar ClickOnce installation dialogs.
Your users will see the update dialog when you make updates available.
WinRT Interop (Breaking Change)
There are several benefits to this new WinRT interop model:
Runtime and Libraries
There were many improvements across the runtime and libraries.
Основы и схожие требования
Для нас критически важно продолжать развиваться как платформа со средствами управления запуском, производительностью, потреблением памяти, надёжностью и диагностики. В то же время целесообразно сосредоточить наши усилия. Мы станем больше работать над повышением производительности и надежности в CoreCLR, а также над улучшением запуска и снижением размера файлов компиляторе Mono AOT. Нам это кажется хорошим сочетанием. Производительность и надежность идут рука об руку, как и скорость запуска со снижением размера файлов.
В улучшение одних характеристик целесообразно вкладывать разные ресурсы, а в улучшение других — нет.
Top-level programs
The led-blink program is a nice compact top-level program example.
You can also see the use of target-typed new , with the assignment to the controller variable. The GpioController type is only defined on the left-hand side of the assignment. The type is inferred on the right-hand side. This new syntax is an alternative to var , which has the type only showing on the right-hand side of the assignment and is inferred on the left-hand side with the var keyword.
Top-level programs can also grow in complexity, by defining methods and taking advantage of types defined in the same or other files. The CharacterLcd sample demonstrates some of those capabilities.
Windows Communication Foundation
Сообщество поддерживает серверные компоненты, дополняющие вышеупомянутые клиентские библиотеки. Репозиторий GitHub можно найти на странице CoreWCF. Серверные компоненты официально не поддерживаются корпорацией Майкрософт. В качестве альтернативы WCF можно рассмотреть gRPC.
Записи: ссылочные типы с семантикой равенства на основе значений и обратимыми изменениями, поддерживаемыми новым выражением with .
Сопоставление реляционного шаблона: расширяет возможности сопоставления шаблонов с реляционными операторами для сравнения оценок и выражений, включая логические шаблоны — новые ключевые слова and , or и not .
Указатели функций: языковые конструкции, которые предоставляют следующие коды операций промежуточного языка (IL): ldftn и calli .
Заключение
Code quality improvements in RyuJIT
Containers
This change has the following benefit for multi-stage builds, with a sample Dockerfile:
Multi-stage build costs with Ubuntu 20.04 Focal:
Pull Image | Before | After |
---|---|---|
sdk:5.0-focal | 268 MB | 232 MB |
aspnet:5.0-focal | 64 MB | 10 KB (manifest only) |
Net download savings: 100 MB (-30%)
Multi-stage build costs with Debian 10 Buster:
Pull Image | Before | After |
---|---|---|
sdk:5.0 | 280 MB | 218 MB |
aspnet:5.0 | 84 MB | 4 KB (manifest only) |
Net download savings: 146 MB (-40%)
This change helps multi-stage builds, where the sdk and the aspnet or runtime image you are targeting are the same version (we expect that this is the common case). With this change, the aspnet pull (for example), will be a no-op, because you will have pulled the aspnet layers via the initial sdk pull.
Итого
Подведем итоги. Стоит ли мигрировать на новый дотнет и ради чего?
Кажется, самое важное, ради чего стоит заморачиваться — это перфоманс. Ускорили практически все и достаточно заметно. Как на низком уровне — через улучшения в GC и JIT — так и на уровне отдельных частей фреймворка. Так что, если вы хотите выиграть в производительности, стоит как минимум попробовать обновить версию фреймворка и замерить, насколько ускорились основные сценарии.
И на этом все! Удачной миграции на новый дотнет. Оставайтесь на связи, мы вернемся с более подробными материалами про современные возможности дотнета.
- Open source и ориентированность на сообщество GitHub.
- Кроссплатформенная реализация.
- Поддержка использования специфических платформозависимых возможностей, таких как Windows Forms и WPF под Windows, а также нативных привязок (bindings) к каждой нативной платформе из Xamarin.
- Высокая производительность.
- Side-by-side инсталляция.
- Маленький размер файлов проектов (SDK-стиль).
- Интерфейс командной строки (CLI) с широкими возможностями.
- Интеграция с Visual Studio, Visual Studio for Mac и Visual Studio Code.
Генераторы исходного кода
Помимо обычной интерполяции строк, существует типизированная интерполяция. При использовании типизированной интерполяции заданный тип должен соответствовать спецификатору формата.
Это похоже на функцию sprintf , которая форматирует строку на основе типобезопасных входных данных.
Application deployment
After writing or updating an application, you need to deploy it for your users to benefit. This might be to a web server, a cloud service, or client machine, and might be the result of a CI/CD flow using a service like Azure DevOps or GitHub Actions.
Improved Dictionary support
It produces the following output.
Platform and Microsoft Support
Nullability annotation improvements
You can see an example of MemberNotNull in the BMxx80 temperature sensors with the following code.
Windows Forms designer
Windows desktop APIs (including Windows Forms, WPF, and WinRT) will only be available when targeting net5.0-windows . You can specify an operating system version, like net5.0-windows7 or net5.0-windows10.0.17763.0 ( for Windows October 2018 Update). You need to target a Windows 10 version if you want to use WinRT APIs.
Cross-platform scenarios can be a bit more challenging, when using the new net5.0-windows TFM. System.Device.Gpio demonstrates a pattern for managing the Windows target-framework if you want to avoid building for Windows or avoid pulling Windows runtime packages on Linux, for example.
Summary of changes:
Рождение проекта
Теперь мы двигаем проект как единая команда. С декабря мы далеко продвинулись в нескольких проектах:
Обновление существующих проектов
Вы можете обновить существующие проекты, обновив целевую платформу следующим образом:
Native exports
- Expose custom native exports.
- Doesn’t require a higher-level interop technology like COM.
- Works cross-platform.
There are existing projects that enable similar scenarios, such as:
Two primary PRs:
Printing environment information
You can install and run the tool with the following commands.
The tool produces output in the following form for your environment.
Performance
Support for fields
JsonSerializer now supports fields. This change was contributed by @YohDeadfall. Thanks!
Produces the following output:
Tools
Support for ICU on Windows
We use the ICU library for Unicode and globalization support, previously only on Linux and macOS. We are now using this same library on Windows 10. This change makes the behavior of globalization APIs such as culture-specific string comparison consistent between Windows 10, macOS, and Linux. We also use ICU with Blazor WebAssembly.
Single file applications
Single file applications are published and deployed as a single file. The app and its dependencies are all included within that file. When the app is run, the dependencies are loaded directly from that file into memory (with no performance penalty).
We had multiple hurdles to overcome to create a true single-file solution. Key tasks were creating a more sophisticated application bundler and teaching the runtime to load assemblies out of binary resources. We also ran into some hurdles that we could not clear.
You can use the following commands to produce single-file apps.
- Framework-dependent single-file app:
- dotnet publish -r linux-x64 --self-contained false /p:PublishSingleFile=true
- dotnet publish -r linux-x64 --self-contained true /p:PublishSingleFile=true
You can also configure single file publishing with a project file.
You can experiment with assembly trimming to reduce the size of your application. It can break apps, by over-trimming, so it is recommended to test your app thoroughly after using this feature. Assembly trimming also removes ahead-of-time-compiled read-to-run native code (for the assemblies that are trimmed), which is there primarily for performance. You will want to test your application for performance after trimming. You can ready-to-run-compile your app after trimmng by using PublishReadyToRun property (and setting to true ).
Читайте также: