Mark!20个。NET6新增的API
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} Bio: {user.Bio} " );
});
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 file
byte [] strBytes = Encoding . UTF8. GetBytes ( "Hello world" );
ReadOnlyMemory buffer1 = new ( strBytes);
await RandomAccess . WriteAsync ( handle, buffer1, 0 );
// Get file length
long length = RandomAccess . GetLength ( handle);
// Read from file
Memory 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 Meter
var meter = new Meter ( "MetricsApp" , "v1.0" );
// Create counter
Counter 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 Listener
void 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 ();
}
检查元素是否可为空的反射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 NotNull
class 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 ); // NotNull
Console . WriteLine ( notNullableArrayNI. ElementType . ReadState ); // Nullable
NullabilityInfo nullableArrayNI = nullabilityInfoContext. Create ( nullableArrayPI);
Console . WriteLine ( nullableArrayNI. ReadState ); // Nullable
Console . WriteLine ( nullableArrayNI. ElementType . ReadState ); // Nullable
class Example
{
public string ?[] NotNullableArray { get ; set ; }
public string ?[]? NullableArray { get ; set ; }
}
ProcessId & ProcessPath
直接通过 Environment 获取进程ID和路径。
int processId = Environment . ProcessId
string 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 missing
app. 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 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} Cos = {cos}" );
// Computes an approximate of 1 / x
double 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} Max = {max} Abs = {abs}" );
Console . WriteLine ( $"Clamp = {clamp} Sign = {sign}" );
// DivRem variants return a tuple
( int quotient, int remainder) = Math . DivRem ( 2 , 7 );
Console . WriteLine ( $"Quotient = {quotient} Remainder = {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() 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);
}
}
[1] Oleg Kyrylchuk: https://hashnode.com/@okyrylchuk
文章来源于全球技术精选 ,作者Oleg Kyrylchuk
打通快递最后一百米监管需介入最前一百米王云帆平台间硝烟又起。据北京商报等媒体近日报道,拼多多旗下的社区团购多多买菜正在试运营代收业务。菜鸟驿站则发出最后通牒,禁止驿站入库多多买菜订单,否则永久清退。有驿站加盟商忧心二选
真实iQOO9Pro使用体验,给准备购买者一个参考本人从首发一周后入手的,用了差不多一个月了。现在简单总结一下优劣,给像我一样准备购买的人一点帮助。先说优点1屏幕好,通透,对眼睛友好,有2k屏(可以在设置里选择开不开)。2微曲屏手
投影仪投天花板是什么体验?从手机到ipad,从按键到刘海屏,人们对于屏幕的需求越来越大了。相比起小屏幕的电视,投影仪产品成为了家居新宠。但对于第一次接触投影仪的朋友来说,是否需要预留投影仪摆放空间成了大问题
Service层和Dao层真的有必要每个类都加上接口吗?简单来说就是看情況。主要看你项目变动情况以及架构人员项目情况比如,项目原来使用的hibernate,后续可能要切换为mybatis,那么dao就需要使用接口。这就不会影响上层代码的
我国首次发现双生病毒逃逸DNA甲基化的新机制近日,中国农业科学院植物保护研究所作物病原生物功能基因组研究创新团队联合国内其他科研单位,首次发现植物病毒可以激活植物的DNA主动去甲基化机制来逃逸植物DNA甲基化介导的防御反应,
互联网快报董明珠建议将工薪阶层税收起征点提至1万元(齐鲁晚报齐鲁壹点综合整理)董明珠建议提高工薪阶层税收起征点,富人应多交税近日,在央视财经对话栏目中,格力电器董事长兼总裁董明珠表示,自己作为人大代表,今年会在会上提出,提高工薪阶
昔日四千多元的小米MIX,如今400元买到手,升级MIUI10更流畅还记得在2016年小米发布MIX初代的时候,那是何等的震撼。MIX也开启了全面屏时代,并且当时一机难求根本抢不到。如今6年过去了,我在咸鱼掏到这台9成新MIX才花了400元,真香。
你们吉利的车机这么惨,要不还是买了魅族吧前两天有个消息,据传吉利要收购魅族了!大伙都觉得这是众望所归。为啥呢?一则是魅族有救了,还有一个原因是希望魅族能救救吉利的极氪001,这车的车机被喷烂了。最近微博上传得很火的一个小
Golang入门到项目实战golang函数golang函数简介函数的go语言中的一级公民,我们把所有的功能单元都定义在函数中,可以重复使用。函数包含函数的名称参数列表和返回值类型,这些构成了函数的签名(signature)
鸿蒙3。0来了,这次,我想批评鸿蒙哈喽,欢迎来到黑马公社鸿蒙系统,我们并不陌生了。截止至华为冬季新品发布会,搭载HarmonyOS(鸿蒙操作系统)设备数突破2。2亿台。用户数量增长迅速,现在鸿蒙3。0系统也很快发布
一夜暴跌7!特斯拉正在走下神坛?昨夜,美股三大三大指数一路走低,科技股重创,各大造车新势力也遭受重创,Rivian跌7。79特斯拉跌7法拉利未来跌6。32Lucid及蔚来跌6,还有一众新能源车企跟跌。受此影响,今
吉利星瑞试驾车在店欢迎到店品鉴深圳深意吉利汽车星瑞展车试驾车已到店欢迎到店品鉴现在预订可享超值政策1。超值换新礼4000元置换补贴(吉利用户专享6000元),2000元增购补贴2。超值金融礼金融至高贴息5000
越大越好浅谈汽车大轮圈的优缺点现在很多人在提车之后的第壹件事儿,就是琢磨着该换个什么又大又酷炫的轮圈。在不少外貌党的眼里,轮圈作为影响汽车外观的重要因素,不换一个与之不同的,恐怕是无法满足的。首先在讨论大轮圈之
吉利星越现金优惠0。75万元现车直售星越现金直降3000元,吉利品牌CMA架构下首款SUV,百公里加速6。8秒,融合多项安全科技,现在预订享多重豪礼1。金融优享首付一成起,最低0月供2。置换优享置换补贴5500元3。
震惊!五菱汽车想干这事小Q巴那我走?前段时间刚和同事讨论,央妈近段时间好像对国内人力资源的问题上显得格外的上心。三胎政策突然就跳了出来,平地一声雷呀。所以说很多事情并不会空穴来风,必然会事出有因。就在前几天,车企团支
iQOO5Pro图赏擦出火花的竞技三色当有人问起,你为什么喜欢iQOO5Pro,我的答案就是它猛!哪儿都猛!今天我终于拿到了iQOO5Pro传奇版,和赛道版不同的是,传奇版的iQOO5Pro背部采用素皮材质,同时在外观
iQOO8亮相ChinaJoy,顶级屏幕终于来了2021年7月30日,一年一度的中国国际数码互动娱乐展览会(简称ChinaJoy)在上海新国际博览中心隆重开展。以超级玩家生而强悍为主题的iQOO品牌展区落地ChinaJoyE4馆
手机级高端工艺下的笔记本,RedmiBookPro首发评测2020年,Redmi发布了不少笔记本产品,像RedmiBook14锐龙版,当时我们可是高喊AMDYES,还有游戏本RedmiG但其中主打轻薄办公的RedmiBookAir13是我
屏下摄像头终于完美,中兴Axon30正式发布7月27日,全新一代屏下摄像手机中兴Axon305G正式发布。作为中兴手机重磅力作,中兴Axon305G屏下摄像技术进一步升级,以商用再度领跑市场的硬核实力开启全屏时代新格局。延续
选购一台工业级一体机,市场较关注的点有哪些?在工业控制领域,智能智控设备应用广泛,无论是系统应用还是具体的设备控制,工业级的智控终端不可获缺。在数字化的大潮下,各领域的企业纷纷进行数字化改造,智能工厂,产线升级,自动化设备控
当国潮与手机相遇,realme真我V15锦鲤手机体验评测我认为的国潮就是结合了传统和现代,将中国元素与潮流融合所带来的一种文化设计。而这几年国潮的崛起,也让咱们传统的文化再次走向了国际化。realme真我选择结合国潮与科技,并携手国家宝
这部影像旗舰,让我爱上超广角,vivoX60Pro评测vivo在2020年末带来了vivoX60系列的两款前菜,而vivoX60与vivoX60Pro在影像上的表现我们也是有目共睹的,当时我带着vivoX60Pro去外拍时就被全新的色