개발언어/C#
[C#] Task.Wait() vs await Task
창용이랑
2023. 5. 12. 17:47
728x90
- Task.Wait은 Task가 끝날 때까지 기다리는 블로킹 동기화 방식
using System;
using System.Threading;
using System.Threading.Tasks;
namespace tstAsyncConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Before");
Task1().Wait();
Console.WriteLine("After");
Console.ReadKey();
}
public static async Task Task1()
{
await Task.Delay(1500);
Console.WriteLine("Finished Task1");
}
}
}
- await은 해당 Task가 완료될 때까지 다른 작업을 진행하다가 작업이 완료되면 해당 작업 이후 남겨진 루틴을 처리하는 논블록 비동기 방식
using System;
using System.Threading;
using System.Threading.Tasks;
namespace tstAsyncConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Before");
callAsync();
Console.WriteLine("After");
Console.ReadKey();
}
public static async void callAsync()
{
await Task1();
}
public static async Task Task1()
{
// await Task.Delay(1500);
await Task.Run(() =>
{
System.Threading.Thread.Sleep(3000);
});
Console.WriteLine("Finished Task1");
}
}
}
출처 : https://blog.naver.com/lsunday/222528740248