Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new API in .NET 6?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the new API in .NET 6?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

DateOnly & TimeOnly

.net 6 introduces two long-awaited types-DateOnly and TimeOnly, which represent the date and time portions of DateTime, respectively.

DateOnly dateOnly = new (2021, 9,25); Console.WriteLine (dateOnly); TimeOnly timeOnly = new (19,0,0); Console.WriteLine (timeOnly); DateOnly dateOnlyFromDate = DateOnly.FromDateTime (DateTime.Now); Console.WriteLine (dateOnlyFromDate); TimeOnly timeOnlyFromDate = TimeOnly.FromDateTime (DateTime.Now); Console.WriteLine (timeOnlyFromDate); Parallel.ForEachAsync

It can control the parallelism of multiple asynchronous tasks.

Var userHandlers = new [] {"users/okyrylchuk", "users/jaredpar", "users/davidfowl"}; using HttpClient client = new () {BaseAddress = new Uri ("https://api.github.com"),};client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue (" DotNet "," 6 ")); ParallelOptions options = new () {MaxDegreeOfParallelism = 3}; await Parallel.ForEachAsync (userHandlers, options, async (uri, token) = > {var user = await client.GetFromJsonAsync (uri, token)) Console.WriteLine ($"Name: {user.Name}\ nBio: {user.Bio}\ n");}); public class GitHubUser {public string Name {get; set;} public string Bio {get; set }} / / Output:// Name: David Fowler// Bio: Partner Software Architect at Microsoft on the ASP.NET team, Creator of SignalR// Name: Oleg Kyrylchuk// Bio: Software developer | Dotnet | C# | Azure// Name: Jared Parsons// Bio: Developer on the C# compilerArgumentNullException.ThrowIfNull ()

The small improvement of ArgumentNullException, which does not need to check null in every method before throwing an exception, now only needs to write a line, similar to response.EnsureSuccessStatusCode ();.

ExampleMethod (null); void ExampleMethod (object param) {ArgumentNullException.ThrowIfNull (param); / / Do something} PriorityQueue

Net 6 new data structure, PriorityQueue, each element of the queue has an associated priority, which determines the order of dequeue, and the elements with low numbers are dequeued first.

PriorityQueue priorityQueue = new (); priorityQueue.Enqueue ("Second", 2); priorityQueue.Enqueue ("Fourth", 4); priorityQueue.Enqueue ("Third 1", 3); priorityQueue.Enqueue ("Third 2", 3); priorityQueue.Enqueue ("First", 1); while (priorityQueue.Count > 0) {string item = priorityQueue.Dequeue (); Console.WriteLine (item);} / / Output:// First// Second// Third 2move / Third 1 / FourthRandomAccess

Provides an offset-based API for reading and writing files in a thread-safe manner.

Using SafeFileHandle handle = File.OpenHandle ("file.txt", access: FileAccess.ReadWrite); / / Write to filebyte [] strBytes = Encoding.UTF8.GetBytes ("Hello world"); ReadOnlyMemory buffer1 = new (strBytes); await RandomAccess.WriteAsync (handle, buffer1, 0); / / Get file lengthlong length = RandomAccess.GetLength (handle); / / Read from fileMemory buffer2 = new (new byte [length]); await RandomAccess.ReadAsync (handle, buffer2, 0); string content = Encoding.UTF8.GetString (buffer2.ToArray ()); Console.WriteLine (content); / / Hello worldPeriodicTimer

Recognize a completely asynchronous "PeriodicTimer" that is more suitable for use in asynchronous scenarios, which has a method WaitForNextTickAsync.

/ / One constructor: public PeriodicTimer (TimeSpan period) using PeriodicTimer timer = new (TimeSpan.FromSeconds (1)); while (await timer.WaitForNextTickAsync ()) {Console.WriteLine (DateTime.UtcNow) / / Output:// 13-Oct-21 19:58:05 PM// 13-Oct-21 19:58:06 PM// 13-Oct-21 19:58:07 PM// 13-Oct-21 19:58:08 PM// 13-Oct-21 19:58:09 PM// 13-Oct-21 19:58:10 PM// 13-Oct-21 19:58:11 PM// 13-Oct-21 19ZeV 5812 PM//... Metrics API

.net 6 implements the OpenTelemetry Metrics API specification with built-in metrics API, and creates the following metrics through the Meter class

Counter

Histogram

ObservableCounter

ObservableGauge

The methods used are as follows:

Var builder = WebApplication.CreateBuilder (args); var app = builder.Build (); / / Create Metervar meter = new Meter ("MetricsApp", "v1.0"); / / Create counterCounter counter = meter.CreateCounter ("Requests"); app.Use ((context, next) = > {/ / Record the value of measurement counter.Add (1); return next (context);}); app.MapGet ("/", () = > "Hello World"); StartMeterListener (); app.Run () / / Create and start Meter Listenervoid StartMeterListener () {var listener = new MeterListener (); listener.InstrumentPublished = (instrument, meterListener) = > {if (instrument.Name = = "Requests" & & instrument.Meter.Name = = "MetricsApp") {/ / Start listening to a specific measurement recording meterListener.EnableMeasurementEvents (instrument, null);}} Listener.SetMeasurementEventCallback ((instrument, measurement, tags, state) = > {Console.WriteLine ($"Instrument {instrument.Name} has recorded the measurement: {measurement}");}); listener.Start ();} check whether the element can be a nullable reflection API

It provides emptiness information and context from reflection members:

ParameterInfo parameter

FieldInfo field

PropertyInfo attribute

EventInfo event

Var example = new Example (); var nullabilityInfoContext = new NullabilityInfoContext (); foreach (var propertyInfo in example.GetType (). GetProperties ()) {var nullabilityInfo = nullabilityInfoContext.Create (propertyInfo); Console.WriteLine ($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");} / / Output:// Name property is Nullable// Value property is NotNullclass Example {public string? Name {get; set;} public string Value {get; set;}} check whether nested elements can be nullable reflective API

It allows you to get nullable information for nested elements, and you can specify that array attributes must be non-empty, but elements can be empty, and vice versa.

Type exampleType = typeof (Example); PropertyInfo notNullableArrayPI = exampleType.GetProperty (nameof (Example.NotNullableArray)); PropertyInfo nullableArrayPI = exampleType.GetProperty (nameof (Example.NullableArray)); NullabilityInfoContext nullabilityInfoContext = new (); NullabilityInfo notNullableArrayNI = nullabilityInfoContext.Create (notNullableArrayPI); Console.WriteLine (notNullableArrayNI.ReadState); / / NotNullConsole.WriteLine (notNullableArrayNI.ElementType.ReadState); / / NullableNullabilityInfo nullableArrayNI = nullabilityInfoContext.Create (nullableArrayPI); Console.WriteLine (nullableArrayNI.ReadState); / / NullableConsole.WriteLine (nullableArrayNI.ElementType.ReadState) / / Nullableclass Example {public string? [] NotNullableArray {get; set;} public string? []? NullableArray {get; set;}} ProcessId & ProcessPath

Get the process ID and path directly through Environment.

Int processId = Environment.ProcessIdstring path = Environment.ProcessPath;Console.WriteLine (processId); Console.WriteLine (path); Configuration added GetRequiredSection ()

It is the same as DI's GetRequiredService (), and if it is missing, an exception is thrown.

WebApplicationBuilder builder = WebApplication.CreateBuilder (args); WebApplication app = builder.Build (); MySettings mySettings = new (); / / Throws InvalidOperationException if a required section of configuration is missingapp.Configuration.GetRequiredSection ("MySettings") .bind (mySettings); app.Run (); class MySettings {public string? SettingValue {get; set;}} CSPNG password secure pseudorandom number generator

You can easily generate sequences of random values from the password secure pseudorandom number generator (CSPNG).

It is useful in the following scenarios:

Key generation

Random number

Salt in some signature schemes

/ / Fills an array of 300 bytes with a cryptographically strong random sequence of values.// GetBytes (byte [] data); / / GetBytes (byte [] data, int offset, int count) / / GetBytes (int count) / / GetBytes (Span data) byte [] bytes = RandomNumberGenerator.GetBytes (300); Native Memory API

.net 6 introduces a new API to allocate native memory, and NativeMemory has methods for allocating and freeing memory.

Unsafe {byte* buffer = (byte*) NativeMemory.Alloc; NativeMemory.Free (buffer); / * This class contains methods that are mainly used to manage native memory. Public static class NativeMemory {public unsafe static void* AlignedAlloc (nuint byteCount, nuint alignment); public unsafe static void AlignedFree (void* ptr); public unsafe static void* AlignedRealloc (void* ptr, nuint byteCount, nuint alignment); public unsafe static void* Alloc (nuint byteCount); public unsafe static void* Alloc (nuint elementCount, nuint elementSize); public unsafe static void* AllocZeroed (nuint byteCount); public unsafe static void* AllocZeroed (nuint elementCount, nuint elementSize) Public unsafe static void Free (void* ptr); public unsafe static void* Realloc (void* ptr, nuint byteCount);} * /} Power of 2

.net 6 introduces a new method for dealing with the power of 2.

'IsPow2' determines whether the specified value is a power of 2.

'RoundUpToPowerOf2' rounds the specified value to the power of 2.

/ / IsPow2 evaluates whether the specified Int32 value is a power of two.Console.WriteLine (BitOperations.IsPow2); / / True// RoundUpToPowerOf2 rounds the specified T:System.UInt32 value up to a power of two.Console.WriteLine (BitOperations.RoundUpToPowerOf2); / / 256WaitAsync on Task

You can more easily wait for the asynchronous task to execute, throwing a "TimeoutException" if the timeout occurs

Task operationTask = DoSomethingLongAsync (); await operationTask.WaitAsync (TimeSpan.FromSeconds (5)); async Task DoSomethingLongAsync () {Console.WriteLine ("DoSomethingLongAsync started."); await Task.Delay (TimeSpan.FromSeconds (10)); Console.WriteLine ("DoSomethingLongAsync ended.");} / / Output:// DoSomethingLongAsync started.// Unhandled exception.System.TimeoutException: The operation has timed out. New Mathematical API

New method:

SinCos

ReciprocalEstimate

ReciprocalSqrtEstimate

New overload:

Min, Max, Abs, Sign, Clamp support nint and nuint

DivRem returns a tuple, including quotient and remainder.

/ New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate// Simultaneously computes Sin and Cos (double sin, double cos) = Math.SinCos (1.57); Console.WriteLine ($"Sin = {sin}\ nCos = {cos}"); / / Computes an approximate of 1 / xdouble recEst = Math.ReciprocalEstimate (5); Console.WriteLine ($"Reciprocal estimate = {recEst}"); / / Computes an approximate of 1 / Sqrt (x) double recSqrtEst = Math.ReciprocalSqrtEstimate (5); Console.WriteLine ($"Reciprocal sqrt estimate = {recSqrtEst}") / New overloads// Min, Max, Abs, Clamp and Sign supports nint and nuint (nint a, nint b) = (5,10); nint min = Math.Min (a, b); nint max = Math.Max (a, b); nint abs = Math.Abs (a); nint clamp = Math.Clamp (abs, min, max); nint sign = Math.Sign (a); Console.WriteLine ($"Min = {min}\ nMax = {max}\ nAbs = {abs}") Console.WriteLine ($"Clamp = {clamp}\ nSign = {sign}"); / / DivRem variants return a tuple (int quotient, int remainder) = Math.DivRem (2,7); Console.WriteLine ($"Quotient = {quotient}\ nRemainder = {remainder}") / / Output:// Sin = 0.9999996829318346 Cos / Reciprocal estimate = 0.000796326710331026 / Reciprocal sqrt estimate = 0.4472135954999579 / Min = 5 / Max = 10 / Abs = 5 / Clamp = 5 / Sign = 1 / Quotient = 0 / Remainder = 2CollectionsMarshal.GetValueRefOrNullRef

This is used when looping or modifying the variable structure in the dictionary, which can reduce the copy copy of the structure and avoid repeated hashing in the dictionary. This is a bit obscure. If you are interested, you can take a look at this.

Https://github.com/dotnet/runtime/issues/27062

Dictionary dictionary = new () {{1, new MyStruct {Count = 100}; int key = 1x ref MyStruct value = ref CollectionsMarshal.GetValueRefOrNullRef (dictionary, key); / / Returns Unsafe.NullRef () if it doesn't exist; check using Unsafe.IsNullRef (ref value) if (! Unsafe.IsNullRef (ref value)) {Console.WriteLine (value.Count); / / Output: 100 / / Mutate in-place value.Count++; Console.WriteLine (value.Count) / / Output: 101} struct MyStruct {public int Count {get; set;}} ConfigureHostOptions

The new ConfigureHostOptions API on IHostBuilder makes it easier to configure applications.

Public class Program {public static void Main (string [] args) {CreateHostBuilder (args). Build (). Run ();} public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .ConfigureHostOptions (o = > {o.ShutdownTimeout = TimeSpan.FromMinutes (10);} Async Scope)

.net 6 introduces a new CreateAsyncScope method, and the existing CreateScope method throws an exception when you deal with IAsyncDisposable's services, which can be solved perfectly with CreateAsyncScope.

Await using var provider = new ServiceCollection () .AddScoped () .BuildServiceProvider (); await using (var scope = provider.CreateAsyncScope ()) {var example = scope.ServiceProvider.GetRequiredService ();} class Example: IAsyncDisposable {public ValueTask DisposeAsync () = > default;}

Encryption class simplification

DecryptCbc

DecryptCfb

DecryptEcb

EncryptCbc

EncryptCfb

EncryptEcb

Static byte [] Decrypt (byte [] key, byte [] iv, byte [] ciphertext) {using (Aes aes = Aes.Create ()) {aes.Key = key; return aes.DecryptCbc (ciphertext, iv, PaddingMode.PKCS7);}} "what are the new API in .NET 6"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report