头图

Today we released .NET 7 Preview 7. This is the last preview release of .NET 7 and the next release will be our first Release Candidate (RC). The dates for .NET Conf 2022 have been announced! Please join us on November 8-10, 2022 to celebrate the release of .NET 7!

Visual Studio 2022 17.3 is also released today with GA support for the .NET Multiplatform Application UI (MAUI). Read the .NET MAUI announcement and listen to .NET Conf: Follow MAUI Live!
This .NET 7 preview includes improvements to System.LINQ, Unix file permissions, low-level structures, p/Invoke source code generation, code generation, and websockets.

You can download .NET 7 Preview 7 for Windows, macOS and Linux.
Installers and binaries
Container images
Linux packages
Release Notes
Known Issues
GitHub issue tracker

.NET 7 Preview 7 has been tested with Visual Studio 17.4 Preview 1. If you want to try .NET 7 in the Visual Studio family of products, we recommend using the Preview Channel version . If you are using macOS, we recommend using the latest Visual Studio 2022 for Mac preview . Now, let's take a look at some of the latest updates in this release.

Simplify sorting with System.LINQ

dotnet/runtime#67194

System.Linq now has methods Order and OrderDescending, which sort IEnumerables according to T.
IQueryable now supports this as well.
Note: This change does not introduce new language features to System.Linq.Expressions.
Usage <br>Previously, you had to call OrderBy/OrderByDescending by referencing your own value.
var data = new[] { 2, 1, 3 };
var sorted = data.OrderBy(static e => e);
var sortedDesc = data.OrderByDescending(static e => e);
Now you can write as:
var data = new[] { 2, 1, 3 };
var sorted = data.Order();
var sortedDesc = data.OrderByDescending();

Support Unix file mode

dotnet/runtime PR #69980

Previously, .NET had no built-in support for getting and setting Unix file permissions, which controlled which users could read, write, and execute files and directories. P/Invoking manually invoking the system is not always easy, as some are exposed in different ways on different distributions. For example, on Ubuntu you might need to call __xstat, on RedHat stat, etc. This makes first-class .NET APIs important.
In Preview 7, we introduced a new enum:
public enum UnixFileMode
{

 None,
OtherExecute, OtherWrite, OtherRead,
GroupExecute, GroupWrite, GroupRead,
UserExecute, UserWrite, UserRead,
 ...

}

And the APIs File.GetUnixFileMode and File.SetUnixFileMode, which get and set the file mode on a path or handle (file descriptor). And a new property on FileInfo and DirectoryInfo called UnixFileMode.
There's also a new overload of Directory.CreateDirectory and a new property on FileStreamOptions that allow you to create a directory or file with a specific schema all at once. Note that when you use these, the umask is still applied as if you were creating a directory or file in the shell.
usage
/Create a new directory with specific permissions
Directory.CreateDirectory("myDirectory", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);

// Create a new file with specific permissions
FileStreamOptions options = new()
{

 Access = FileAccess.Write,
Mode = FileMode.Create,
UnixCreateMode =  UnixFileMode.UserRead | UnixFileMode.UserWrite,

};
using FileStream myFile = new FileStream("myFile", options);

// Get the mode of the existing file
UnixFileMode mode = File.GetUnixFileMode("myFile");

// set the mode of the existing file
File.SetUnixFileMode("myFile", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);

Check out all the new Unix file mode APIs.

Big thanks to @tmds , a long-time Red Hat contributor who proposed, designed and implemented this feature.

Low-level structure improvements: ref field support

The .NET 7 runtime now fully supports ref fields in the ByRefLike type (ie ref struct). There is an extensive language design behind this highly anticipated feature, which users can read:Low-level structural improvements . With this feature, types that previously required specialized handling at runtime (for example, Span<T> and ReadOnlySpan<T>) can now be fully implemented in C#.

LibraryImport P/Invoke Source Generator

dotnet/runtime#60595

The LibraryImport source generator is now available to all users in a supported way. Over 18 months of effort, this source generator has been designed as a drop-in replacement for most DllImport use, both in runtime production and in user code. The .NET libraries all adopt LibraryImport and have shipped source-generated marshalling code since .NET 7 Preview 1 .
The source code generator ships with .NET 7 TFM and is ready to use. To gain the benefits of source generation marshalling, replace usage of DllImport with LibraryImport. There are analyzers and fixers that can help with this process.
usage
forward
public static class Native
{

 [DllImport(nameof(Native), CharSet = CharSet.Unicode)]
public extern static string ToLower(string str);

}
back
public static class Native
{

 [LibraryImport(nameof(Native), StringMarshalling = StringMarshalling.Utf16)]
public static partial string ToLower(string str);

}
There is an analyzer and code fix that automatically converts your DllImport property to LibraryImport. For preview 7 it is optional. Add dotnet_diagnostic.SYSLIB1054.severity=suggestion to your editor configuration file to enable Transform Analyzer as a diagnostic.
Design documentation and details on marshalling custom types can be found at docs/design/libraries/LibraryImportGenerator .

ClientWebSocket upgrade response details

dotnet/runtime#25918

ClientWebSocket has not previously provided any details about the upgrade response. However, information about response headers and status codes can be important in both failure and success scenarios.
In the case of failure, the status code can help differentiate between retrievable and non-retrievable errors (the server doesn't support web sockets at all, just a tiny transient error). The header may also contain additional information on how to handle this situation.
The headers are helpful even in the case of a successful web socket connection, for example, they can contain a token bound to the session, some information related to the subprotocol version, or the server might be about to shut down, etc.
usage
ClientWebSocket ws = new();
ws.Options.CollectHttpResponseDetails = true;
try
{

 await ws.ConnectAsync(uri, default);

// success scenario

 ProcessSuccess(ws.HttpResponseHeaders);
ws.HttpResponseHeaders = null; // 清理(如果需要)

}
catch (WebSocketException)
{

 // 失败场景
if (ws.HttpStatusCode != null)
{
    ProcessFailure(ws.HttpStatusCode, ws.HttpResponseHeaders);
}

}

Improvements to CodeGen

Big thanks to JIT community contributors for contributing to these community PRs!
@MichalPetryka Fixed issue #71632 in PR # 71633 making getTypeForPrimitiveValueClass treat different symbols as different types.
@shushanhf made 2 fixes in LoongArch64.
@singleaccretion made 20 PR contributions during Preview 7.
@SkiFoD Optimized to use Min/Max intrinsics if one of the arguments is constant ( PR #69434 ).
• For Arm664, @a74nh implemented the first part of #67894 in PR #71616 , which generates csel and ccmp for conditional compare and select instructions (issue #55364 ).

Loop optimization

In Preview 7, we made several improvements to loop optimization.
PR #71184 strengthens the checking of loop tables to better check loop integrity, as described in #71084.
PR #71868 Don't compress blocks around loops • PR #71659 Adjust weights of blocks with loops inside contours in non-contour methods • PR #71504 Improvements to loop boosting • PR #70271 Optimize multidimensional array access. It improves latency by 67% (Performance Link).
Also, enabled hot/cold split for exception handlers in PR #71236 .

Contributor Spotlight: Hugh Bellamy

A big thank you to all our community members. We greatly appreciate your thoughtful contributions. We asked contributor @hughbe to share his thoughts.

image.png

In Hugh's own words:
The first app I developed was when I was a teenager. Although "Hughser", a C# wrapper around the WebBrowser component, unfortunately didn't win the browser wars, .NET was my first window into the world of software development. After a few years of developing apps for iOS, I got a renewed interest in .NET when roslyn, corefx, and coreclr were open sourced. I'd love to have the opportunity to dig into the black box and see how the SDK I'm using works. My first PR in November 2015 was to clean up and add tests for various methods on System.String. (As is clear to anyone who has looked at my contribution history, cleaning, improving and adding tests became my specialty!). I quickly gained the confidence to contribute and became one of the most active contributors to .NET open source. I now contribute to various .NET Foundation projects including corefx/coreclr/runtime, roslyn, xunit, mono, wpf and winforms. One of the highlights of my contribution was definitely meeting the team and giving a shout out to the .NET Keynote when I was flown by Microsoft to Seattle for Microsoft Build 2019! I've also won three consecutive Microsoft MVP awards for my contributions, which I'm very proud of.
In the past, my contributions to .NET helped me get an internship as a junior developer as a teenager. I am currently a management consultant specializing in financial services data and analytics. Although I have less time now than I did in high school and college, I still have a strong focus on the .NET open source ecosystem and maintain several .NET open source projects on GitHub under the username @hughbe . Coding and open source have always been my hobbies and things that I love to combine with my work. .As a political science undergraduate, I am interested in how technology is used in political and social contexts. For example, as an intern at an NGO in Cambodia, I developed a Facebook scraping platform in .NET, some of which I open sourced.

Contributing to .NET has been an incredible experience - as a teenager, I was working remotely with people I never met almost every day. The Microsoft team and the rest of the open source community are very helpful, insightful, and open to challenges. There are many ways to get started, whether by submitting or reviewing issues , documentation, and PRs, so get started today!

Targeting .NET 7

To target .NET 7, you need to use the .NET 7 Target Framework Moniker (TFM) in your project file. For example: <TargetFramework>net7.0</TargetFramework>
Below is the full set of .NET 7 TFMs, including operation-specific TFMs.
• net7.0
• net7.0-android
• net7.0-ios
• net7.0-maccatalyst
• net7.0-macos
• net7.0-tvos
• net7.0-windows
We want an easy upgrade from .NET 6 to .NET 7. Please report any breaking changes you find while testing your existing applications with .NET 7.

support

.NET 7 is a Short Term Support (STS) release, which means it will receive free support and patches for 18 months from the release date. It is important to note that all versions are of the same quality. The only difference is the supported length. For more information on the .NET support policy, see the .NET and .NET Core Official Support Policy.

We recently changed the "Current" name to "Short Term Support (STS)". We are rolling out this change .

breaking changes

Trim and Native AOT: Trim all assemblies by default To better meet user expectations and produce smaller, more efficient applications, Trim now trims all assemblies in console apps by default. This change only affects applications published with PublishTrimmed=true, and only applications with existing trim warnings. It also only affects normal .NET applications that don't use the Windows desktop, Android, iOS, WASM or ASP.NET SDKs.

previous behavior

Previously, only assemblies that opted in to <IsTrimmable>true</IsTrimmable> in the library project file were trimmed.

new behavior

Beginning with .NET 7, trimming trims all assemblies in the app by default. Applications that may have previously used PublishTrimmed may not work in .NET 7. However, only apps with pruning warnings are affected. If your app doesn't have a trim warning, the behavior change shouldn't have any detrimental effect and may reduce the app size.
For example, an application that uses Newtonsoft.Json or System.Text.Json without generating source code to serialize and deserialize a type in a user project may have run before the change because the type in the user project is fully preserved. However, there will be one or more trim warnings (warning codes ILxxxx). Now, the types in the user project are pruned and serialization may fail or produce unexpected results.
If your app does have pruning warnings, you may see behavior changes or exceptions. For example, an application that uses Newtonsoft.Json or System.Text.Json without generating source code to serialize and deserialize a type in a user project may have run before the change because the type in the user project is fully preserved. However, there will be one or more trim warnings (warning codes ILxxxx). Now, the types in the user project are pruned and serialization may fail or produce unexpected results.

Recommended Action

The best solution is to resolve all trim warnings in the application. To revert to the previous behavior, set the TrimMode property to partial, which was the pre-.NET 7 behavior.
<TrimMode>partial</TrimMode>
The default .NET 7+ value is full:
<TrimMode>full</TrimMode>

Other major changes

You can find the latest list of .NET 7 breaking changes by reading the Breaking Changes in .NET 7 document. It lists breaking changes by region and version, with links to detailed descriptions.
To see what breaking changes have been proposed but still under review, follow the Proposed .NET Breaking Changes GitHub issue.

route map

A distribution of .NET includes products, libraries, runtimes, and tools, and represents collaboration between multiple teams within and outside Microsoft. You can learn more about these by reading the product roadmap:
ASP.NET Core 7 and Blazor Roadmap
EF 7 Roadmap
ML.NET
.NET MAUI
WinForms
WPF
NuGet
Roslyn
Runtime


We thank you for all your support and contributions to .NET. Please try .NET 7 Preview 7 and let us know what you think!

Go to view .NET 7 Preview 7, and download and install related programs.
image.png
Long press to identify the QR code
Click to view .NET 7 Preview 7~


微软技术栈
418 声望994 粉丝

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。