What’s New In .NET 6 APIs?

In the last .Net post, we saw What’s new in C# 9.0. In this article, we will see what’s new in .NET 6 APIs and all the exciting new set of these API methods.

.Net 6
Source: Visual Studio Magazine

.NET 6 is is well on the way currently it is in preview 6 as of writing of this article. There are some new sets of APIs in .NET 6 and ASP.NET Core. This is because they are a huge favorite among the .NET developer community. Hence these have been specially implemented on popular demand.

Note: All code source is taken from credit devblogs.microsoft.com

List of some of the New .NET 6 APIs

  • A Secured Random Pseudo Number Generator
  • The New Parallel.ForEachAsync Method
  • Read and Write Files Without Using A File Stream
  • Access Process Ids And Process Paths
  • Required Configuration Section Helper
  • Chunk An IEnumerable To Batches Using LINQ
  • Introducing the new MaxBy and MinBy methods
  • The Power Of Powers of 2 Method
  • Yield The Incomplete Await with WaitAsync
  • Bye Bye Null Checks, Welcome ThrowIfNull
  • The Timer API Becomes Modern

A Secured Random Pseudo Number Generator

Below method is used for generating random numbers from Cryptographically Secure Pseudorandom Number Generator i.e. CSPNG.

// Generate a set of 100 random bytes
byte[] bytes = RandomNumberGenerator.GetBytes(100);

The New Parallel.ForEachAsync Method

There is a Parallel.ForEachAsync method. It is to schedule any asynchronous task allowing us to control the degree of parallelism.

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

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);
    }
});

Read and Write Files Without Using A File Stream

Also in .NET 6 now there’s a new API for reading and writing files without using a FileStream. Yes without a File Stream. It also will support overlapping reads and writes at an offset and scatter / gather IO.

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

Console.WriteLine(length);

Access Process Ids And Process Paths

Now you can access a process id and a process path without allocating any new process object as shown below.

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

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

Required Configuration Section Helper

A much needed helper to for throwing an error if any required section of a configuration file is missing is also added.

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

// Throw if the section not configured
configuration.GetRequiredSection("MyOptions").Bind(options);

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

Chunk An IEnumerable To Batches Using LINQ

Now there is a new helper to help chunk in batch 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);
    }
}

Introducing the new MaxBy and MinBy methods

var people = GetPeople();

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

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

public record Person(string Name, int Age);

The Power Of Powers of 2 Method

If you need to work with powers of 2 then below helper will sort you out.

using System.Numerics;

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

Console.WriteLine(bufferSize);

Yield The Incomplete Await with WaitAsync

A better way to wait for a task to complete asynchronously. The below code yields the await if it isn’t yet completed in 20 seconds. But the operation might be running still hence this is going to be used for non cancellable work.

Task operationTask = SomeLongRunningOperationAsync();

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

Bye Bye Null Checks, Welcome ThrowIfNull

Now no more null checking via null in every method. Throw if it is null via just one line of code as shown below.

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

The Timer API Becomes Modern

Lastly, there is a modern timer which is fully async. There are also less catches the other timers had like no asynchronous callbacks, lifetime problems and other nitty gritty issues.

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

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

Summary

These are just some of the new .NET APIs coming in the version .NET 6. Also there are a lot of performance improvements in .NET 6. Currently as of now, the .NET 6 is in Preview Mode so you can try out these APIs presently. What do you think about these new set of methods, let us discuss in the comments section. Do share this article if you found it useful.

Hitesh Boricha

I have a little over a decade experience in the IT industry. Having worked in various roles in this industry, I am passionate about technology.

One thought to “What’s New In .NET 6 APIs?”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.