본문 바로가기

CancellationToken

C# 비동기 스트림(IAsyncEnumerable) 처리와 응용 IAsyncEnumerable는 대용량 I/O를 지연(lazy) 처리하면서 메모리를 아끼고, 자연스럽게 back-pressure(생산과 소비 균형)를 제공하는 C# 8+의 비동기 스트림입니다. 파일/네트워크/DB 등 느린 소스를 한 줄(하나)씩 받아 처리할 때 유용합니다.1. 기본 문법: async iterator + await foreach생산자는 async iterator로 IAsyncEnumerable을 만들고, 소비자는 await foreach로 순회합니다.using System; using System.Collections.Generic;using System.Runtime.CompilerServices;using System.Threading;using System.Threading.Tasks.. 더보기
C# CancellationToken으로 작업 취소 구현하기 CancellationToken은 비동기/병렬 작업을 ‘협조적’으로 취소하기 위한 표준 도구입니다. 토큰을 메서드에 전달하고, 해당 메서드가 수시로 토큰을 확인해 스스로 중단하도록 설계합니다.1. 기본 사용법CancellationTokenSource로 토큰을 만들고 메서드에 전달합니다. 작업 내에서는 ThrowIfCancellationRequested 또는 IsCancellationRequested를 사용해 주기적으로 확인합니다.using System;using System.Threading;using System.Threading.Tasks;static async Task DoWorkAsync(CancellationToken token){ for (int i = 0; i 2. I/O 작업 취소 (.. 더보기
C# 비동기 프로그래밍 async/await 1. 개념 설명async/await는 비동기 작업을 선언적으로 표현해 I/O 대기 시간을 효율적으로 처리합니다. 메서드를 async로 표시하고 Task/Task를 반환하며, await는 현재 스레드를 차단하지 않고 작업이 완료되면 이어서 실행합니다. 이를 통해 UI 응답성을 유지하고 서버에서 더 많은 동시 요청을 처리할 수 있습니다.2. 코드 예제아래 예제는 웹 페이지 문자열 길이와 인위적 딜레이 작업을 동시에 시작한 뒤 결과를 출력합니다.using System;using System.Net.Http;using System.Threading.Tasks;class Program{ static async Task FetchLengthAsync() { using var client = .. 더보기