介绍
接下来我将给大家重点介绍一下.Net 6 之后的一些新的变更,文章都是来自于外国大佬的文章,我这边进行一个翻译,并加上一些自己的理解和解释。
源作者链接:https://blog.okyrylchuk.dev/20-new-apis-in-net-6#heading-a-new-periodictimer
正文
Power of 2
.NET 6 引入了使用 2 的幂的新助手。
- 'IsPow2' 评估指定值是否为 2 的幂。
- 'RoundUpToPowerOf2' 如果超过了最大值,即2的30此幂,将设置成最大值,如果这个数的二进制是零的话返回1,即输入0返回1。
// 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
等待异步任务
您可以更轻松地等待任务异步完成执行。操作超时时抛出“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 supports nint and nuint
- DivRem variants return a tuples
// 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 / 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}\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
它返回一个可以就地更新的结构值的引用。它不是用于一般用途,而是用于高性能场景。
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; }
}
配置主机选项
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);
});
}
创建异步范围
.NET 6 引入了一个新的CreateAsyncScope方法来创建AsyncServiceScope。处置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;
}
加密操作的简化调用模式
SymmetricAlgorithm上的新方法可在有效负载已在内存中时避免流:
- 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);
}
}
结语
联系作者:加群:867095512 @MrChuJiu