关于.net:您所不知的新-NET-6-API的那些事

9次阅读

共计 4257 个字符,预计需要花费 11 分钟才能阅读完成。

.NET 6 行将推出,接下来的文章中咱们将在.NET 和 ASP.NET Core 中分享一些令人惊喜的新 API,它们是由咱们杰出的 .NET 开发人员社区间接驱动的,让咱们开始逐个理解吧!

行将推出:
https://devblogs.microsoft.co…

读写文件

在 .NET 6 中,有一个新的 API 能够在不应用 FileStream 的状况下读取 / 写入文件。它还反对扩散 / 汇集 IO(多个缓冲区)和给定文件偏移量的笼罩读取和写入。

using Microsoft.Win32.SafeHandles;
using SafeFileHandle handle = File.OpenHandle("ConsoleApp128.exe");
long length = RandomAccess.GetLength(handle);

Console.WriteLine(length);

过程门路和 ID

有几种新办法能够在不调配新过程对象的状况下拜访过程门路和过程 ID:

int pid = Environment.ProcessId;
string path = Environment.ProcessPath;

Console.WriteLine(pid);
Console.WriteLine(path);

CSPNG(明码平安伪随机数生成器)

从 CSPNG(明码平安伪随机数生成器)生成随机数比以往更容易:

// Give me 200 random bytes
byte[] bytes = RandomNumberGenerator.GetBytes(200);

Parallel.ForEachAsync

咱们最终增加了 Parallel.ForEachAsync,这是一种调度异步工作的办法,可让您管制并行度:

var urlsToDownload = new [] 
{
    "https://dotnet.microsoft.com",
    "https://www.microsoft.com",
    "https://twitter.com/davidfowl"
};

var client = new HttpClient();

await Parallel.ForEachAsync(urlsToDownload, async (url, token) =>
{var targetPath = Path.Combine(Path.GetTempPath(), "http_cache", url);

    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {using FileStream target = File.OpenWrite(targetPath);

        await response.Content.CopyToAsync(target);
    }
})

配置 Helpes

咱们增加了一个帮忙程序,以便在短少必须的配置局部时更容易抛出异样:

var configuration = new ConfigurationManager();
var options = new MyOptions();

// This will throw if the section isn't configured
configuration.GetRequiredSection("MyOptions").Bind(options);

class MyOptions
{public string? SettingValue { get; set;}
}

LINQ

还有大量新的 LINQ 办法。在这个版本中它失去了很多人的青睐。这是将任何 IEnumerable 分块的新 Helper:

int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 9).Chunk(3))
{Console.WriteLine($"Chunk {chunkNumber++}");
    foreach (var item in chunk)
    {Console.WriteLine(item);
    }
} 

更多的 LINQ

更多 LINQ!当初有 MaxBy 和 MinBy 办法:

var people = GetPeople();

var oldest = people.MaxBy(p => p.Age);
var youngest = people.MinBy(p => p.Age);

Console.WriteLine($"The oldest person is {oldest.Age}");
Console.WriteLine($"The youngest person is {youngest.Age}");

public record Person(string Name, int Age);

Power of 2

不要把数学放在你的脑海里?以下是一些应用 Powerof 2 的新 Helper:

using System.Numerics;

uint bufferSize = 235;
if (!BitOperations.IsPow2(bufferSize))
{bufferSize = BitOperations.RoundUpToPowerOf2(bufferSize);
}

Console.WriteLine(bufferSize);

WaitAsync 改良

当初有一种更简略(并且正确实现)的办法来期待工作异步实现。如果 10 秒内未实现,以下代码将放弃 await。该操作可能仍在运行!这是用于不可勾销的操作!

Task operationTask = SomeLongRunningOperationAsync();

await operationTask.WaitAsync(TimeSpan.FromSeconds(10));

ThrowIfNull

在抛出异样之前不再须要在每个办法中查看 null。它当初只需一行简略的代码。

void DoSomethingUseful(object obj)
{ArgumentNullException.ThrowIfNull(obj);
}

应用 NativeMemory

如果您想应用 CAPI 来分配内存,因为您是 l33thacker 或须要调配本机内存,那就应用这个吧。别忘了开释!

using System.Runtime.InteropServices;

unsafe
{byte* buffer = (byte*)NativeMemory.Alloc(100);

    NativeMemory.Free(buffer);
}

Posix 信号处理

这是对于对 Posix 信号处理的本机反对,咱们还在 Windows 上模仿了几个信号。

using System.Runtime.InteropServices;

var tcs = new TaskCompletionSource();

PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{Console.WriteLine($"{context.Signal} fired");
    tcs.TrySetResult();});

await tcs.Task;

新的 Metrics API

咱们在 .NET 6 中增加了一个基于 @opentelemetry 的全新 Metrics API。它反对维度,十分高效,并且将为风行的指标接收器提供导出器。

using System.Diagnostics.Metrics;

// This is how you produce metrics

var meter = new Meter("Microsoft.AspNetCore", "v1.0");
Counter<int> counter = meter.CreateCounter<int>("Requests");

var app = WebApplication.Create(args);

app.Use((context, next) =>
{counter.Add(1, KeyValuePair.Create<string, object?>("path", context.Request.Path.ToString()));
    return next(context);
});

app.MapGet("/", () => "Hello World");

您甚至能够收听和计量:

var listener = new MeterListener();
listener.InstrumentPublished = (instrument, meterListener) =>
{if(instrument.Name == "Requests" && instrument.Meter.Name == "Microsoft.AspNetCore")
    {meterListener.EnableMeasurementEvents(instrument, null);
    }
};

listener.SetMeasurementEventCallback<int>((instrument, measurement, tags, state) =>
{Console.WriteLine($"Instrument: {instrument.Name} has recorded the measurement: {measurement}");
});

listener.Start();

古代定时器 API

古代计时器 API(我认为这是 .NET 中的第 5 个计时器 API)。它是齐全异步的,不会有遇到其余计时器那样的问题,例如对象生命周期问题,没有异步回调等。

var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));

while (await timer.WaitForNextTickAsync())
{Console.WriteLine(DateTime.UtcNow);
}

总结

这只是 .NET 6 中新 API 的一小部分示例。无关更多信息,请查看 .NET 6 发行阐明 API 差别。此外,Stephen 也写了一篇对于.NET6 性能改良 的精彩博客,因而请务必浏览。最初,不要遗记 下载.NET 6 预览版 并立刻试用新的 API。

.NET 6 发行阐明 API 差别:
https://github.com/dotnet/cor…
.NET6 性能改良:
https://devblogs.microsoft.co…
下载 .NET 6 预览版:
https://dotnet.microsoft.com/…


这里有更多微软官网学习材料和技术文档,扫码获取免费版!
内容将会不定期更新哦!

正文完
 0