头图

.NET 6 is coming soon, in the next article we will share some amazing new APIs in .NET and ASP.NET Core, they are directly driven by our excellent .NET developer community, let us start one by one Understand it!

Coming soon:
https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-7/

Read and write files

In .NET 6, there is a new API to read/write files without using FileStream. It also supports scatter/gather IO (multiple buffers) and overwrite reading and writing of a given file offset.

using Microsoft.Win32.SafeHandles;
using SafeFileHandle handle = File.OpenHandle("ConsoleApp128.exe");
long length = RandomAccess.GetLength(handle);

Console.WriteLine(length);

Process path and ID

There are several new ways to access the process path and process ID without allocating a new process object:

int pid = Environment.ProcessId;
string path = Environment.ProcessPath;

Console.WriteLine(pid);
Console.WriteLine(path);

CSPNG (password secure pseudo-random number generator)

Generating random numbers from CSPNG (cryptographically secured pseudo-random number generator) is easier than ever:

// Give me 200 random bytes
byte[] bytes = RandomNumberGenerator.GetBytes(200);

Parallel.ForEachAsync

We finally added Parallel.ForEachAsync, which is a method of scheduling asynchronous work that allows you to control the degree of parallelism:

var urlsToDownload = new [] 
{
    "https://dotnet.microsoft.com",
    "https://www.microsoft.com",
    "https://twitter.com/davidfowl"
};

var client = new HttpClient();

await Parallel.ForEachAsync(urlsToDownload, async (url, token) =>
{
    var targetPath = Path.Combine(Path.GetTempPath(), "http_cache", url);

    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        using FileStream target = File.OpenWrite(targetPath);

        await response.Content.CopyToAsync(target);
    }
})

Configure Helpes

We added a helper to make it easier to throw exceptions when a required configuration part is missing:

var configuration = new ConfigurationManager();
var options = new MyOptions();

// This will throw if the section isn't configured
configuration.GetRequiredSection("MyOptions").Bind(options);

class MyOptions
{
    public string? SettingValue { get; set;}
}

LINQ

There are also a large number of new LINQ methods. In this version it has been loved by many people. This is the new helper that blocks any IEnumerable:

int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 9).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber++}");
    foreach (var item in chunk)
    {
        Console.WriteLine(item);
    }
} 

More LINQ

More LINQ! Now there are MaxBy and MinBy methods:

var people = GetPeople();

var oldest = people.MaxBy(p => p.Age);
var youngest = people.MinBy(p => p.Age);

Console.WriteLine($"The oldest person is {oldest.Age}");
Console.WriteLine($"The youngest person is {youngest.Age}");

public record Person(string Name, int Age);

Power of 2

Don't put mathematics in your head? Here are some new helpers that use Powerof 2:

using System.Numerics;

uint bufferSize = 235;
if (!BitOperations.IsPow2(bufferSize))
{
    bufferSize = BitOperations.RoundUpToPowerOf2(bufferSize);
}

Console.WriteLine(bufferSize);

WaitAsync improvements

There is now a simpler (and correctly implemented) way to wait for the task to complete asynchronously. If it is not completed within 10 seconds, the following code will give up await. The operation may still be running! This is for non-cancelable operations!

Task operationTask = SomeLongRunningOperationAsync();

await operationTask.WaitAsync(TimeSpan.FromSeconds(10));

ThrowIfNull

It is no longer necessary to check for null in every method before throwing an exception. It now only requires a simple line of code.

void DoSomethingUseful(object obj)
{
    ArgumentNullException.ThrowIfNull(obj);
}

Use NativeMemory

If you want to use CAPI to allocate memory, because you are l33thacker or need to allocate native memory, then use this. Don't forget to release!

using System.Runtime.InteropServices;

unsafe
{
    byte* buffer = (byte*)NativeMemory.Alloc(100);

    NativeMemory.Free(buffer);
}

Posix signal processing

This is about native support for Posix signal processing. We also simulated several signals on Windows.

using System.Runtime.InteropServices;

var tcs = new TaskCompletionSource();

PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{
    Console.WriteLine($"{context.Signal} fired");
    tcs.TrySetResult();
});

await tcs.Task;

New Metrics API

We have added a new Metrics API based on @opentelemetry in .NET 6. It supports dimensions, is very efficient, and will provide exporters for popular indicator receivers.

using System.Diagnostics.Metrics;

// This is how you produce metrics

var meter = new Meter("Microsoft.AspNetCore", "v1.0");
Counter<int> counter = meter.CreateCounter<int>("Requests");

var app = WebApplication.Create(args);

app.Use((context, next) =>
{
    counter.Add(1, KeyValuePair.Create<string, object?>("path", context.Request.Path.ToString()));
    return next(context);
});

app.MapGet("/", () => "Hello World");

You can even listen and measure:

var listener = new MeterListener();
listener.InstrumentPublished = (instrument, meterListener) =>
{
    if(instrument.Name == "Requests" && instrument.Meter.Name == "Microsoft.AspNetCore")
    {
        meterListener.EnableMeasurementEvents(instrument, null);
    }
};

listener.SetMeasurementEventCallback<int>((instrument, measurement, tags, state) =>
{
    Console.WriteLine($"Instrument: {instrument.Name} has recorded the measurement: {measurement}");
});

listener.Start();

Modern timer API

Modern timer API (I think this is the fifth timer API in .NET). It is completely asynchronous and will not encounter the problems of other timers, such as object life cycle problems, no asynchronous callbacks, etc.

var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));

while (await timer.WaitForNextTickAsync())
{
    Console.WriteLine(DateTime.UtcNow);
}

Summarize

This is just a small sample of the new APIs in .NET 6. For more information, please see .NET 6 Release Notes API Differences . In addition, Stephen also wrote an .NET6 performance improvement , so please be sure to read it. Finally, don't forget to 6 preview version and try out the new API immediately.

.NET 6 release notes API differences:
https://github.com/dotnet/core/tree/main/release-notes/6.0/preview/api-diff
.NET6 performance improvements:
https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6/
Download the preview version of .NET 6:
https://dotnet.microsoft.com/download

Here are more Microsoft official learning materials and technical documents, scan the code to get the free version!
The content will be updated from time to time!
image.png


微软技术栈
418 声望994 粉丝

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