Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [링크 복사], [링크+제목 복사]
조회: 7412
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

.NET 6에 포함된 신규 BCL API

다음과 같은 좋은 소개 글이 있군요. ^^

A preview of all of the new runtime features added in .NET 6 
; https://threadreaderapp.com/thread/1422816504060416002.html

현재(2021-08-10) .NET 6 preview 6이 나온 상태이고, 위의 글에 소개된 기능들은 모두 테스트가 가능합니다. 그럼, 이참에 같이 따라 해 볼까요? ^^

우선, FileStream을 사용하지 않고 C++처럼 저수준의 Handle만으로 파일 연산을 할 수 있는 API가 추가되었습니다.

static void lowLevelFileOperation()
{
    using var handle = File.OpenHandle("ConsoleApp1.exe");
    var length = RandomAccess.GetLength(handle);
    Console.WriteLine($"FileLength: {length}");
}

그다음, "Process" 개체 생성 없이 현재 프로세스에 한해 경로와 id를 접근할 수 있는 속성이 Environment에 추가되었습니다.

static void getProcessInfoWihtoutProcessObject()
{
    var pid = Environment.ProcessId;
    var path = Environment.ProcessPath;

    Console.WriteLine($"ProcessId: {pid}");
    Console.WriteLine($"ProcessPath: {path}");
}

GC를 최소화하기 위한 눈물 겨운 노력으로 보입니다. ^^

CSPNG(Cryptographically Secure Pseudorandom Number Generator)의 사용법도 아주 단순한 유형으로 하나 제공합니다. 가령, 4바이트 무작위 정수를 반환받고 싶다면 이렇게 호출할 수 있습니다.

static void produceRandomInt4()
{
    var bytes = RandomNumberGenerator.GetBytes(4);
    Console.WriteLine($"Random Int4: {BitConverter.ToInt32(bytes)}");
}

Parallel.ForEachAsync도 추가되었습니다.

static async Task parallelDownload()
{
    var urlsToDownload = new[]
    {
        "https://www.bing.com",
        "https://www.google.com",
        "https://search.yahoo.com/"
    };

    var client = new HttpClient();

    // https://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames
    string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
    var path = Path.GetDirectoryName(Environment.ProcessPath);

    await Parallel.ForEachAsync(urlsToDownload, async (url, token) =>
    {
        Regex r = new Regex(string.Format("[{0}]", Regex.Escape(invalidChars)));

        var targetPath = Path.Combine(path, r.Replace(url, "_") + ".txt");
        var response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            using var target = File.OpenWrite(targetPath);
            await response.Content.CopyToAsync(target);

            Console.WriteLine($"{targetPath}: downloaded");
        }
    });
}

IEnumerable<T> LINQ 확장 메서드에도 역시 도우미 메서드들이 많이 추가되었다고 합니다. 아래는 컬렉션의 개수를 특정 묶음으로 나누는 Chunk 메서드이고,

static void ImprovedLinqMethods()
{
    int chunkNumber = 1;

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

        foreach (var item in chunk)
        {
            Console.WriteLine(item);
        }
    }
}

/* 출력 결과
Chunk 1
0
1
2
3
Chunk 2
4
5
6
7
Chunk 3
8
*/

새롭게 MaxBy, MinBy가 기존의 IEnumerable.Max/Min을 보완해 추가되었습니다.

var people = new People[]
{
    new People{ Name = "tester", Age = 30 },
    new People{ Name = "admin", Age = 25 },
};

Console.WriteLine(people.Max((elem) => elem.Age)); // 출력 결과: 30
Console.WriteLine(people.Max(new AgeComparer())); // 출력 결과: People { Name = tester, Age = 30 }

Console.WriteLine(people.MaxBy((elem) => elem.Age)); // 출력 결과: People { Name = tester, Age = 30 }
Console.WriteLine(people.MinBy((elem) => elem.Age)); // 출력 결과: People { Name = tester, Age = 30 }

보는 바와 같이, 기본형이 아닌 경우 Max/Min은 해당 인스턴스를 반환받고 싶다면 IComparer를 구현한 개체를 반환해야 했지만, MaxBy/MinBy는 비교할 멤버를 지정하면서도 개체를 결과로 반환해 주고 있습니다.

BitOperations에 추가된 IsPow2, RoundUpToPowerOf2 메서드는 그냥 추가되었다는 것만 기억해도 좋을 듯싶고,

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

    Console.WriteLine(bufferSize); // 출력 결과 256
}

비동기 메서드 호출 시, 해당 작업이 특정 시간 내에 끝나지 않으면 예외를 발생시키도록 만드는 것은 기억해 둘 만하겠습니다.

static async Task WaitOnly10Sec()
{
    var task = Task.Run(() =>
    {
        return Task.Delay(5 * 1000);
    });

    // await task; // 원래는 5초를 대기해야 하지만,

    Console.WriteLine($"[start] Task.Run: {DateTime.Now}");
    await task.WaitAsync(TimeSpan.FromSeconds(2));
    Console.WriteLine($"[end]   Task.Run: {DateTime.Now}");
}

/* 실행 결과: 2초가 지나 예외 발생
[start] Task.Run: 2021-08-08 오후 10:54:05
Unhandled exception. System.TimeoutException: The operation has timed out.
   at ConsoleApp1.Program.WaitOnly10Sec()
   at ConsoleApp1.Program.Main(String[] args)
   at ConsoleApp1.Program.
(String[] args) in ConsoleApp1.dll:token 0x600000e+0xc */




ASP.NET Core의 경우 Configuration.GetRequiredSection 메서드가 추가되어 필수 설정이 없는 경우 예외를 발생시키는 것을 지원합니다.

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

public void ConfigureServices(IServiceCollection services)
{
    var options = new MyOptions();
    // 추가된 appsettings.json에 "MyOptions"가 없는 경우 예외 발생
    // System.InvalidOperationException: 'Section 'MyOptions' not found in configuration.'
    Configuration.GetRequiredSection("MyOptions").Bind(options);

    services.AddControllers();
}

따라서, 이 오류로 인해 개발자는 명시적으로 해당 속성을 appsettings.json에 추가해야 한다는 것을 인지할 수 있습니다.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "MyOptions": {
        "SettingValue":  "test_var_1",
    }
}

이와 함께, @OpenTelemetry 지원을 위한 API를 내장하게 되었습니다. 가령 아래의 예제는 ASP.NET Core Web API 프로젝트에 추가했기 때문에 Web API의 호출 수를 제공하게 됩니다.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseAuthorization();

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

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, 원 글에서는 이 외에도 Preview 7에 포함된 3가지 기능도 함께 소개하고 있습니다.

Make improvements to signal handling on .NET applications
; https://github.com/dotnet/runtime/issues/50527

Implement NativeMemory #54006
; https://github.com/dotnet/runtime/pull/54006

Add ArgumentNullException.ThrowIfNull
; https://github.com/dotnet/runtime/pull/55594

기타!

Using the new PriorityQueue from .NET 6 (Preview 2)
; https://blog.elmah.io/using-the-new-priorityqueue-from-net-6/




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/19/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-08-27 01시32분
New .NET 6 APIs driven by the developer community
; https://devblogs.microsoft.com/dotnet/new-dotnet-6-apis-driven-by-the-developer-community/

해당 API들이 전부 외부 개발자 커뮤니티로부터 추가된 것이라고 합니다. ^^
정성태

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13498정성태12/23/20232810닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232291오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232305Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232315Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232497Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232535닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232259개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232231Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232337개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232132개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232066오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232379개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232193개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232159개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232295닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232810닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232261개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232573개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232281개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232464닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232199닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232257닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232116개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232302닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232132C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...