[译]. NET 6 新增API - 中
介绍
接下来我将给大家重点介绍一下.Net 6 之后的一些新的变更,文章都是来自于外国大佬的文章,我这边进行一个翻译,并加上一些自己的理解和解释。
源作者链接:https://blog.okyrylchuk.dev/20-new-apis-in-net-6#heading-a-new-periodictimer
正文
Metrics API
.NET6实现了OpenTelemetry Metrics 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<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 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<int>((instrument, measurement, tags, state) =>
{
Console.WriteLine($"Instrument {instrument.Name} has recorded the measurement: {measurement}");
});
listener.Start();
}
Reflection API for Nullability Information(可空性信息的反射 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; }
}
进程路径和 ID
您可以访问流程路径和 ID,而无需分配新的流程实例。
int processId = Environment.ProcessId
string path = Environment.ProcessPath;
Console.WriteLine(processId);
Console.WriteLine(path);
一个新的配置助手
.NET 6 中添加了一个新的配置帮助程序“GetRequiredSection”。如果缺少必需的配置部分,它将引发异常。
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<byte> data)
byte[] bytes = RandomNumberGenerator.GetBytes(300);
本机内存 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);
}*/
}
结语
联系作者:加群:867095512 @MrChuJiu