20 个 .NET 6 新增的 API

7d5bc1d4573523fd3446a41921106fdb.png

DateOnly & TimeOnly

.NET 6 引入了两种期待已久的类型 - DateOnly 和 TimeOnly, 它们分别代表DateTime的日期和时间部分。

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

它可以控制多个异步任务的并行度。

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<GitHubUser>(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# compiler

ArgumentNullException.ThrowIfNull()

ArgumentNullException 的小改进, 在抛出异常之前不需要在每个方法中检查 null, 现在只需要写一行, 和 response.EnsureSuccessStatusCode(); 类似。

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

PriorityQueue

.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。

PriorityQueue<string, int> 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 2// Third 1// Fourth

RandomAccess

提供基于偏移量的 API,用于以线程安全的方式读取和写入文件。

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

PeriodicTimer

认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 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 19:58:12 PM// ...

Metrics API

.NET 6 实现了 OpenTelemetry Metrics API 规范, 内置了指标API, 通过 Meter 类创建下面的指标

•Counter•Histogram•ObservableCounter•ObservableGauge

使用的方法如下:

var builder = WebApplication.CreateBuilder(args);var app = builder.Build();// Create Metervar meter = new Meter("MetricsApp", "v1.0");// Create counterCounter<int> counter = meter.CreateCounter<int>("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<int>((instrument, measurement, tags, state) =>    {        Console.WriteLine($"Instrument {instrument.Name} has recorded the measurement: {measurement}");    });    listener.Start();}

检查元素是否可为空的反射API

它提供来自反射成员的可空性信息和上下文:

•ParameterInfo 参数
•FieldInfo 字段
•PropertyInfo 属性
•EventInfo 事件

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

检查嵌套元素是否可为空的反射API

它允许您获取嵌套元素的可为空的信息, 您可以指定数组属性必须为非空,但元素可以为空,反之亦然。

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

直接通过 Environment 获取进程ID和路径。

int processId = Environment.ProcessIdstring path = Environment.ProcessPath;Console.WriteLine(processId);Console.WriteLine(path);

Configuration 新增 GetRequiredSection()

和 DI 的 GetRequiredService() 是一样的, 如果缺失, 则会抛出异常。

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 密码安全伪随机数生成器

您可以从密码安全伪随机数生成器 (CSPNG) 轻松生成随机值序列。

它对于以下场景中很有用:

•密钥生成•随机数•某些签名方案中的盐

// 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<byte> data)byte[] bytes = RandomNumberGenerator.GetBytes(300);

Native Memory API

.NET 6 引入了一个新的 API 来分配本机内存, NativeMemory 有分配和释放内存的方法。

unsafe{    byte* buffer = (byte*)NativeMemory.Alloc(100);    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 引入了用于处理 2 的幂的新方法。

•'IsPow2' 判断指定值是否为 2 的幂。•'RoundUpToPowerOf2' 将指定值四舍五入到 2 的幂。

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

WaitAsync on Task

您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”

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.

新的数学API

新方法:

•SinCos•ReciprocalEstimate•ReciprocalSqrtEstimate

新的重载:

•Min, Max, Abs, Sign, Clamp 支持 nint 和 nuint•DivRem 返回一个元组, 包括商和余数。

// 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 = 0.0007963267107331026// Reciprocal estimate = 0.2// Reciprocal sqrt estimate = 0.4472135954999579// Min = 5// Max = 10// Abs = 5// Clamp = 5// Sign = 1// Quotient = 0// Remainder = 2

CollectionsMarshal.GetValueRefOrNullRef

这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂,有兴趣的可以看看这个

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

Dictionary<int, MyStruct> dictionary = new(){    { 1, new MyStruct { Count = 100 } }};int key = 1;ref MyStruct value = ref CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);// Returns Unsafe.NullRef<TValue>() 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

IHostBuilder 上的新 ConfigureHostOptions API, 可以更简单的配置应用。

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 引入了一种新的CreateAsyncScope方法, 当您处理 IAsyncDisposable 的服务时现有的CreateScope方法会引发异常, 使用 CreateAsyncScope 可以完美解决。

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

加密类简化

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

全文完...

作者: Oleg Kyrylchuk[1]

原文: https://blog.okyrylchuk.dev/

相关链接

[1] Oleg Kyrylchuk: https://hashnode.com/@okyrylchuk

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/294164.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

中国学生的最大噩梦,都来源于这个男人

全世界只有3.14 % 的人关注了爆炸吧知识会通中西经世致用说到中国古代的“全才”&#xff0c;一般人都会脱口而出沈括、张衡、祖冲之....而在明朝&#xff0c;有这么一位少有人知的“全才”式科学家&#xff0c;他的研究领域包括天文、历法、数学、军事、农业、水利....和上述的…

BASE64 编码和解码

依赖jar: import org.apache.commons.codec.binary.Base64; BASE64和其他相似的编码算法通常用于转换二进制数据为文本数据&#xff0c;其目的是为了简化存储或传输。更具体地说&#xff0c;BASE64算法主要用于转换二进 制数据为ASCII字符串格式。Java语言提供了一个非常好的BA…

类和类之间的关系解析-1

一、泛化关系 泛化关系也称继承关系&#xff0c;指的是一个类&#xff08;称为子类、子接口&#xff09;继承另外的一个类&#xff08;称为父类、父接口&#xff09;的功能&#xff0c;并可以增加它自己的新功能的能力。在Java中继承关系通过关键字extends明确标识&#xf…

转:智能卡测试操作系统技术

具有稳定、可靠的卡内操作系统是智能卡正常工作的基础&#xff0c;智能卡操作系统控制外界与智能卡之间的通信&#xff0c;管理卡片的存储空间&#xff0c;并且在卡内对于各种命令进行处理&#xff0c;所以在COS 开发过程中有必要对COS 进行充分且全面的测试。COS 的主要特点: …

Android之添加快捷方式(Shortcut)到手机桌面

在两个手机上测试,发现小米手机上添加了快捷方式后不能移除,三星手机可以。权限 要在手机桌面上添加快捷方式,首先需要在manifest中添加权限。 <!-- 添加快捷方式 --><uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"…

C# 使用阿里云发送短信

最近有个项目&#xff0c;短信服务使用的是阿里云的&#xff0c;想要使用阿里云平台的短信服务&#xff0c;首先要注册一个阿里云账号&#xff0c;由于发送短信消息需要用到短信签名、短信模板ID&#xff08;已添加并通过审核&#xff09;1、注册阿里云账号&#xff08;地址&am…

如果太阳系毁灭,这种神秘粒子就是真凶!

185年12月7日这一天&#xff0c;东汉中平二年乙丑&#xff0c;一位天文学家观测到天空出现了一颗极其明亮的星体&#xff0c;他并不知道这意味着什么。这颗突然出现于苍穹之中的星星在夜空中照耀了八个月后&#xff0c;又忽然消逝了。《后汉书天文志》中留下了这段记载&#xf…

Centos7 安装gitlab 8.7.5

简介&#xff1a;GitLab 是一个用于仓库管理系统的开源项目。使用Git作为代码管理工具&#xff0c;并在此基础上搭建起来的web服务。1. Web框架使用Ruby on Rails。2. 基于MIT代码发布协议。3. 需要gitolite协同工作。安装要求&#xff1a;ruby 1.9.3MySQLgitgitoliteredis如果…

ocx c++

引用&#xff1a;http://www.baike.com/wiki/ocx ocx&#xff0c;使用它可以很快地在网址、台式应用程序、以及开发工具中加入特殊的功能。 编辑摘要目录 [ 隐藏 ]1 定义2 用途ocx - 定义 ActiveX控件.ActiveX控件是可重用的软件组件。 ocx - 用途 使用它可以很快地在网址、台式…

男人会为女人改变多少

男人会为女人改变多少 女人都想改造男人   从前有人说&#xff0c;女人征服男人&#xff0c;然后通过男人征服世界&#xff1b;而现在是女人改造男人&#xff0c;然后男人按照女人的意愿改造世界。女人喜欢男人&#xff0c;这八成是错不了的&#xff0c;但女人永远不满意男人…

Andorid之BINDSERVICE的使用方法总结

bindService用于绑定一个服务。这样当bindService(intent,conn,flags)后,就会绑定一个服务。这样做可以获得这个服务对象本身,而用startService(intent)的方法只能启动服务。 bindService方式的一般过程: ①新建Service类BindService。在BindService类里新建内部类MyBinder…

linux说明管道的作用,Linux管道及重定向的用途是什么

1、重定向在Linux中有时我们在命令的执行过程中&#xff0c;不想将执行结果显示到屏幕上&#xff0c;或者将其结果输出到其他位置这时就需要重定向来解决这个问题了首先了解一下Linux中的3种I/O设备&#xff1a;0&#xff1a;标准输入1&#xff1a;标准输出2&#xff1a;标准错…

磨刀不误砍柴工—Exceptionless搭配log4net记录日志

Exceptionless专注于.net平台提供实时错误和日志报告。主要包括&#xff1a;错误通知、智能分组异常、详细错误报告堆栈跟踪、支持离线、UI查看重要错误和确定优先级、仪表板上的统计信息和趋势、对异常标记为已修复&#xff0c;监视回归、将事件标记为关键等。主要是用于展示、…

豆瓣9.6分!再一次被BBC的纪录片震惊!

英国广播公司BBC的纪录片素来就是高质量的代名词&#xff0c;推出的《地球无限》(Planet Earth)、《地球的力量》(Earth The Power of the Planet)、《冷血生命》(Life In Cold Blood)等片不仅在英国播放时获得极高收视&#xff0c;还获得艾美奖等多个国际奖项的肯定&#xff0…

C++中事件机制的简洁实现

事件模型是被广泛使用的好东西&#xff0c;但是C标准库里没有现成的&#xff0c;其他实现又复杂或者不优雅&#xff0c;比如需要使用宏。现在VC11可以用在XP下了&#xff0c;那么就痛快的拿起C11提供的先进设施组合出一个轻便的实现吧。 为了达到简洁的目的&#xff0c;需要放弃…

监测京东商品价格波动

写着玩的&#xff0c;不用再去每天看要买的商品是否降价&#xff0c;如果降价就发布一条推文。 #!/usr/bin/env python # coding: utf-8 import tweepy import requests import re import sys import datetime import json # 京东的编码是gbk reload(sys) sys.setdefaultencodi…

Andorid之Log图文详解(Log.v,Log.d,Log.i,Log.w,Log.e)的用法总结

在调试代码的时候我们需要查看调试信息&#xff0c;那我们就需要用Android Log类。 android.util.Log常用的方法有以下5个&#xff1a;Log.v() Log.d() Log.i() Log.w() 以及 Log.e() 。根据首字母对应VERBOSE&#xff0c;DEBUG,INFO, WARN&#xff0c;ERROR。 1、Log.v 的调…

SharePoint 2010 master page 控件介绍(5):其他

转&#xff1a;http://blog.csdn.net/lgm97/article/details/6409227 <!-- 处理搜索按下“enter”键和点击后退按钮 --> <input type"text" name"__spDummyText1" style"display:none;" size"1"/> <input type"te…

linux iotop rpm,iotop命令_Linux iotop 命令用法详解:用来监视磁盘I/O使用状况的工具...

iotop命令是一个用来监视磁盘I/O使用状况的top类工具。iotop具有与top相似的UI&#xff0c;其中包括PID、用户、I/O、进程等相关信息。Linux下的IO统计工具如iostat&#xff0c;nmon等大多数是只能统计到per设备的读写情况&#xff0c;如果你想知道每个进程是如何使用IO的就比较…

.NET 6新特性试用 | LINQ功能改进

前言.NET6为LINQ添加了多个新API&#xff0c;在本文中&#xff0c;我们将始终使用User类逐一演示这些添加到LINQ中的内容&#xff1a;public class User {public string Name { get; set; }public int Age { get; set; } }*By方法包括下列方法&#xff1a;DistinctBy: 根据指定…