[C#] await 연산자

c# 2023. 1. 4. 11:24
728x90

await 은 피연산자가 나타내는 비동기 작업이 완료될 때까지 바깥쪽 비동기 메서드를 일시 중단.

비동기 작업이 완료되면 await 은 작업 결과를 반환(있다면)

이미 완료된 작업의 피연산자에 await 이 적용되면 바깥쪽 메서드를 중지하지 않고 작업 결과를 즉시 반환함

await 은 비동기 메서드를 관리하는 스레드를 차단하지 않는다

 

using System;
using System.Net.Http;
using System.Threading.Tasks;

class AwaitOperator
    {
        public static async Task _AwaitOperator()
        {
            Task<int> downloading = DownloadDocsMainPageAsync();
            Console.WriteLine($"{nameof(_AwaitOperator)}: Launched downloading");

            int bytesLoaded = await downloading;
            Console.WriteLine($"{nameof(_AwaitOperator)}: Downloaded {bytesLoaded} bytes.");
        }
        private static async Task<int> DownloadDocsMainPageAsync()
        {
            Console.WriteLine($"{nameof(DownloadDocsMainPageAsync)} : About to start downloading.");
            var client = new HttpClient();
            byte[] content = await client.GetByteArrayAsync("https://docs.microsoft.com/en-us/");
            Console.WriteLine($"{nameof(DownloadDocsMainPageAsync)}: Finished downloading.");
            return content.Length;
        }
    }

 

 

 

Main 메서드에 Task를 추가하여 본문에서 await 연산자를 사용할 수 있도록 비동기화

 

 

using System;
using System.Threading.Tasks;

class Program
{
	static async Task Main(string[] agrs)
    {
    	Console.WriteLine("--------------AwaitOperator--------------");
        await AwaitOperator._AwaitOperator();
    }
}

 

728x90

'c#' 카테고리의 다른 글

[C#] Interface  (0) 2023.01.05
[C#] 순수 함수  (0) 2023.01.04
[C#] 함수형 프로그래밍  (0) 2023.01.04
[C#] operator-overloading 연산자 오버로드  (0) 2023.01.04
[Console]Keypress  (0) 2022.11.09
Posted by 바르마스
,