ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[译]. NET 6 新增API - 中

2022-01-17 10:02:55  阅读:168  来源: 互联网

标签:Console nuint unsafe void 新增 API static NET public


介绍

接下来我将给大家重点介绍一下.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

公众号

标签:Console,nuint,unsafe,void,新增,API,static,NET,public
来源: https://www.cnblogs.com/MrChuJiu/p/15812264.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有