New .NET 6 features driven by the developer community

As the release of .NET 6 approaches, Microsoft has published a very interesting post which recapitulates the new features included in .NET 6 which have been piloted by the developer community. New features that developers will necessarily appreciate because of this, according to the post, which at first glance does not seem wrong. Here are a few :

Read / write files

.NET 6 features a new low-level API to allow reading / writing of files without using a file stream (FileStream). The API also supports multi-buffer I / O and overlapping reads and writes at a given file offset.

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

Console.WriteLine (length);

Paths and process identifiers

There are several new ways to access a 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);

Improved WaitAsync

There is now a much easier way to wait for a task to complete asynchronously.

Task operationTask = SomeLongRunningOperationAsync ();

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

Adding Parallel.ForEachAsync

Arrives Parallel.ForEachAsync, a way to schedule an asynchronous job that lets you 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);
}
});

ThrowIfNull

No need to check if an argument received by a method is null before throwing an exception. One line of code is enough:

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

Back to top button