워크/C# 5.0
Async/Await
Dev A.i
2023. 8. 28. 15:30
async와 await 키워드를 사용하여 비동기 프로그래밍을 구현한 C# 코드 예시입니다.
이 예시에서는 두 가지 비동기 메서드를 만들어서, 그것들을 사용하여 어떻게 비동기적으로 작업을 수행하는지 보여줍니다.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Start downloading...");
string content = await DownloadWebsiteContentAsync("https://www.example.com");
Console.WriteLine("Downloaded content length: " + content.Length);
Console.WriteLine("Download complete!");
int result = await ComputeValueAsync();
Console.WriteLine($"Computed value: {result}");
}
static async Task<string> DownloadWebsiteContentAsync(string url)
{
using (HttpClient client = new HttpClient())
{
string content = await client.GetStringAsync(url);
return content;
}
}
static async Task<int> ComputeValueAsync()
{
await Task.Delay(2000); // This simulates some async operation
return 42; // Just a sample value
}
}
- DownloadWebsiteContentAsync 메서드는 주어진 URL의 내용을 비동기적으로 다운로드하여 문자열로 반환합니다.
- ComputeValueAsync 메서드는 비동기 작업을 시뮬레이션하기 위해 2초 동안 대기한 후 숫자 42를 반환합니다.
- Main 메서드에서 두 개의 비동기 메서드를 호출하며, await 키워드를 사용하여 비동기 작업의 완료를 기다립니다.
이 코드를 실행하면, "Start downloading..." 메시지가 출력된 후, 비동기적으로 웹사이트의 내용을 다운로드하고, 그 다음에 "Download complete!" 메시지가 출력됩니다.