Current location - Quotes Website - Personality signature - Mark. 20 new APIs in. Network 6
Mark. 20 new APIs in. Network 6
NET 6 introduces two long-awaited types-dateonly and TimeOnly, which represent the date and time parts of DateTime respectively.

DateOnly DateOnly = new(202 1,9,25);

Console. WriteLine(date only);

TimeOnly timeOnly = new ( 19,0,0);

Console. WriteLine(time only);

date only dateOnlyFromDate = date only。 FromDateTime (date and time. Now);

Console. WriteLine(dateOnlyFromDate);

time only time onlyfromdate = time only。 FromDateTime (date and time. Now);

Console. WriteLine(time onlyfromdate);

It can control the parallelism of multiple asynchronous tasks.

var userHandlers = new []

{

"user /okyrylchuk",

"user /jaredpar",

"User/David Fowle"

};

Use HttpClient client = new ()

{

BaseAddress = new Uri (""),

};

Clients. DefaultRequestHeaders。 User agent. add(new ProductInfoHeaderValue(" dot net "," 6 "));

ParallelOptions option = new ()

{

MaxDegreeOfParallelism = 3

};

Wait for parallelism. foreach sync(user handlers,options,async ( uri,token)= & gt;

{

Var user = await client. GetFromJsonAsync & ltGitHubUser & gt(uri,token);

Console. WriteLine ( $ "Name: {user。 Name} Resume: {User. bio }”;

});

Public class GitHubUser

{

Common string name {get setting; }

Common string Bio {get setting; }

}

//Output:

//Name: David Fowler

//Resume: Cooperative software architect of Microsoft ASP.NET team, founder of SignalR.

//

//Name: Oleg Kirichuk

// Bio: Software Developer | Dotnet | C# | Azure

//

//Name: jared Parsons

//Bio:Developer on c# compiler

A small improvement of ArgumentNullException, you don't need to check null in every method before throwing an exception, now you just need to write one line, and response. AssureSuccessstatusCode(); Similar.

example method(null);

Void sample method (object parameter)

{

ArgumentNullException。 ThrowIfNull(param);

//Do something

}

Added data structure. The PriorityQueue of. NET 6 has an associated priority, which determines the dequeue order, and the elements with small numbers are dequeued first.

Priority queue & ltstring, int> priority queue = new ();

Priority queue. Join the team ("seconds", 2);

Priority queue. Join the team ("fourth", 4);

Priority queue. Enqueue ("the third 1", 3);

Priority queue. Join the team ("the third 2", 3);

Priority queue. Join the team ("first",1);

while ( priorityQueue。 Count & gt0 )

{

string item = priorityQueue。 dequeue();

Console. WriteLine (project);

}

//Output:

//First of all

//sec

//The third 2

//The third 1

//Fourth

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

Use SafeFileHandle handle = File. OpenHandle ( "file.txt ",access : FileAccess。 Read and write);

//Write file

Byte [] strBytes = encoding. UTF8。 GetBytes(" Hello world ");

ReadOnlyMemory buffer 1 = new(strBytes);

Waiting for random access. WriteAsync ( handle,buffer 1,0);

//Get the file length

Length = RandomAccess. GetLength (handle);

//Read from file

Memory buffer2 = new (new byte [length]);

Waiting for random access. ReadAsync ( handle,buffer2,0);

String content = encoding. UTF8。 GetString ( buffer2。 ToArray());

Console. WriteLine (content); //Hello world

Knowing a completely asynchronous "PeriodicTimer" is more suitable for asynchronous scenes. It has a WaitForNextTickAsync method.

//A constructor: public periodic timer (timespan period)

Use periodic timer timer = new (timespan. From seconds (1));

While (wait for the timer. WaitForNextTickAsync())

{

Console. WriteLine (date and time. utc now);

}

//Output:

// 13-Oct-2 1 19:58:05PM

// 13-Oct-2 1 19:58:06PM

// 13-Oct-2 1 19:58:07PM

// 13-Oct-2 1 19:58:08PM

// 13-Oct-2 1 19:58:09PM

// 13-Oct-2 1 19:58: 10PM

// 13-Oct-2 1 19:58: 1 1PM

// 13-Oct-2 1 19:58: 12PM

// ...

. NET 6 implements the open measurement API specification and has built-in indicator API. The following indicators are created through the Meter class.

? counter

? bar chart

? Observable counter

? Observable instrument

The method used is as follows:

Var builder = application. CreateBuilder (parameter);

var app = builder。 build();

//Create a meter

var meter = new Meter ( "MetricsApp "," v 1.0 ");

//Create a counter

Counter counter = meters. create counter(" Requests ");

app。 Use ((context, next)= & gt;;

{

//Record the measured value

Counter. Add (1);

Return to the next (context);

});

app。 MapGet ( "/",()= & gt《Hello World》);

startmetelistener();

app。 run();

//Create and start the instrument listener

void StartMeterListener()

{

var listener = new meter listener();

Audience. instrument published =(instrument,meter listener)= & gt;

{

If (the instrument. Name == "Request" & Instrument. Rice. Name == "MetricsApp ")

{

//Start listening to specific measurement records.

Meterlstenerenablemeasurementevents (instrument, empty);

}

};

Audience. SetMeasurementEventCallback ((instrument, measurement, label, status) =>

{

Console. WriteLine($ " Instrument { Instrument。 Name} recorded measurement value: {measurement} ";

});

Audience. start();

}

It provides nullability information and context of reflection members:

? Parameter information parameter

? FieldInfo field

? PropertyInfo property

? EventInfo event

Var example = newexample ();

var nullability info context = new nullability info context();

Foreach (var propertyInfo in the example. GetType()。 GetProperties())

{

var nullability info = nullability info context。 create(property info);

Console. WriteLine ( $ "{propertyInfo。 The Name} property is {nullabilityInfo. WriteState }”);

}

//Output:

// Name attribute can be empty.

//Attribute value is not empty.

Class example

{

Public string? Name {get setting; }

Common string value {get setting; }

}

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

type Example type = type of(Example);

property info notNullableArrayPI = example type。 GetProperty (nameof (example. NotNullableArray));

property info nullableArrayPI = example type。 GetProperty (nameof (example. nullable array));

nullabilityinfocext nullabilityinfocext = new();

NullabilityInfo notNullableArrayNI = nullabilityinfocext。 create(notNullableArrayPI);

Console. WriteLine ( notNullableArrayNI。 ReadState); // NotNull

Console. WriteLine ( notNullableArrayNI。 ElementType。 ReadState); //can be empty

NullabilityInfo nullableArrayNI = nullabilityinfocext。 create(nullableArrayPI);

Console. WriteLine ( nullableArrayNI。 ReadState); //can be empty

Console. WriteLine ( nullableArrayNI。 ElementType。 ReadState); //can be empty

Class example

{

Public string? []NotNullableArray { get; Settings; }

Public string? []? NullableArray {get setting; }

}

Get the process ID and path directly from the environment.

Int processId = environment. ProcessId

String path = environment. ProcessPath

Console. WriteLine(processId);

Console. WriteLine (path);

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

web application builder builder = web application。 CreateBuilder (parameter);

WebApplication app = builder。 build();

my settings my settings = new();

//InvalidOperationException will be thrown if the required configuration part is missing.

app。 Configuration. GetRequiredSection ( "MySettings ")。 bind(my settings);

app。 run();

Classify my settings

{

Public string? Set value {get setting; }

}

You can easily generate a sequence of random values from a cryptographically secure pseudo-random number generator (CSPNG).

It is useful in the following situations:

? Key generation

? random digits

? Some signature schemes

//Fill a 300-byte array with an encrypted sequence of strong random values.

//GetBytes(byte[]data);

// GetBytes(byte[] data, int offset, int count)

// GetBytes(int count)

// GetBytes (span data)

byte[]bytes = RandomNumberGenerator。 GetBytes(300);

NET 6 introduces a new API to allocate NativeMemory, which has methods to allocate and release memory.

dangerous

{

byte * buffer =(byte *)native memory。 alloc( 100);

Natural memory. Free (buffer);

/* This class contains methods mainly used to manage the local memory.

Public static class local memory

{

public unsafe static void * aligned alloc(nuint byteCount,nuint alignment);

Public unsafe static void aligned free (void * ptr);

Public unsafe static void * AlignedRealloc (void * ptr, nuint byteCount, nu int alignment);

Public unsafe static void * alloc (nu int byte count);

public unsafe static void * Alloc(numint element count,numint elementSize);

Public unsafe static void * alloczeroed (Nuint bytecount);

public unsafe static void * AllocZeroed(nuint element count,nuint elementSize);

public unsafe static void Free(void * ptr);

Public unsafe static void * Realloc (void * ptr, nu int bytecount);

}*/

}

NET 6 introduces a new method to deal with the power of 2.

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

? "RoundUpToPowerOf2" rounds the specified value to a power of 2.

// IsPow2 calculates whether the specified Int32 value is a power of 2.

Console. WriteLine ( BitOperations。 ispow 2( 128)); //true

//roundupowerof2 rounds the specified T:System. The maximum value of UInt32 is a power of 2.

Console. WriteLine ( BitOperations。 rounduppowerof 2(200)); // 256

You can wait for the asynchronous task to execute more easily, and if it times out, "TimeoutException" will be thrown.

task operation task = DoSomethingLongAsync();

Wait for operationTask. WaitAsync ( TimeSpan。 from seconds(5));

Asynchronous task DoSomethingLongAsync ()

{

Console. Writeline ("DosomethingLongAsync has been started." );

Waiting for the task. Delay (time span. From seconds (10));

Console. Writeline ("DosomethingLongAsync has ended." );

}

//Output:

//dosomethinglonggasync has been started.

//Unhandled exception. The operation has timed out.

New method:

? Sinkos

? Reciprocating straight line

? Reciprocating test

New overload:

? Minimum value, maximum value, Abs, symbol, clamp bracket nint and nuint.

? DivRem returns a tuple, including quotient and remainder.

//New methods SinCos, ReciprocalSqrtEstimate and ReciprocalQrTest Estimate

//calculate Sin and Cos at the same time

(double sin, double cos) = mathematics. Sinkos (1.57);

Console. WriteLine($ " Sin = { Sin } Cos = { Cos } ");

//Calculate the approximate value of1/x.

double recEst = Math。 Reciprocating motion (5);

Console. WriteLine ($ "reciprocal estimate = {latest}");

//Calculate the approximate value of 1/Sqrt(x)

double recSqrtEst = Math。 reciprocalsqrtestimeta(5);

Console. WriteLine ($ "reciprocal sqrt estimate = {recsqrtest}");

//New overload

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

(nint a,nint b ) = ( 5, 10);

Nint min = mathematics. Min ( a,b);

Nint max = mathematics. Max ( a,b);

Nint abs = mathematics. ABS(a);

Nintcamp = math. Clamp (absolute, minimum, maximum);

Nint symbol = mathematics. Mark (a);

Console. WriteLine($ " Min = { Min } Max = { Max } Abs = { Abs } ");

Console. WriteLine($ " Clamp = { Clamp } Sign = { Sign } ");

// DivRem variable returns a tuple.

(int quotient, int remainder) = Math. DivRem ( 2,7);

Console. WriteLine ($ "quotient = {quotient} remainder = {remainder}");

//Output:

// Sin = 0.99999968293 18346

//Cos = 0.0007963267 10733 1026

//reciprocal estimate = 0.2

//reciprocal sqrt estimated value = 0.4472 135954999579

// Min = 5

// Max = 10

// Abs = 5

// Clamp = 5

// Sign = 1

//Quotient = 0

//Remainder = 2

This is used when looping or modifying the knot variable structure in the dictionary, which can reduce the repetition of the structure and avoid the repeated hash calculation in the dictionary. This is a bit obscure. Anyone interested can take a look at this.

/dotnet/runtime/issues/27062

Dictionary & ltint, mystery & gt dictionary = new ()

{

{1, new MyStruct {Count = 100}}

};

int key = 1;

ref my struct value = ref collection marshal。 GetValueRefOrNullRef (dictionary, key);

//Returns Unsafe. If it does not exist, it is null ref (); Check that it is unsafe to use. IsNullRef (reference value)

If (! Not safe. IsNullRef (reference value)

{

Console. WriteLine (value. Count); //Output: 100

//In situ variation

Value. count++;

Console. WriteLine (value. Count); //Output: 10 1

}

Structure MyStruct

{

Public int Count {get setting; }

}

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

Open course

{

Public static void Main (string [] args)

{

CreateHostBuilder (parameter). Build (). run();

}

Public static ihostbuilder createhostbuilder (string [] args) = >

Host. CreateDefaultBuilder (parameter)

. ConfigureHostOptions(o = & gt;

{

oh ShutdownTimeout = TimeSpan。 from minutes( 10);

});

}

NET 6 introduces a new CreateAsyncScope method. When dealing with the services of IAsyncDisposable, the existing CreateScope method will throw an exception, which can be solved perfectly by using CreateAsyncScope.

Use var provider = new service collection () to wait.

. AddScoped & lt example & gt ()

. BuildServiceProvider();

Waiting for use (var scope = provider. CreateAsyncScope())

{

Var example = range. Service provider. GetRequiredService & lt Example & gt ();

}

Class example: IAsyncDisposable

{

public value task dispose async()= & gt; Default;

}

? decode

? Decrypt Cfb

? Decryption b

? EncryptCbc

? EncryptCfb

? EncryptEcb

Static byte [] decryption (byte [] key, byte [] iv, byte [] ciphertext)

{

Use (aesaes aes = aes. Create())

{

aes。 Key = key

Return to aes. DecryptCbc (ciphertext, iv, PaddingMode). pkcs 7);

}

}