C# 5.0에는 async와 await 예약어를 이용하여 비동기 호출을 마치 동기 방식처럼 호출하는 코드를 작성할 수 있다.
📝 동기 호출
static void Main(string[] args)
{
SyncPrint();
}
static void SyncPrint()
{
using (FileStream fs = new FileStream(@"C:\TestWorkspace\fileTest.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buf = new byte[fs.Length];
fs.Read(buf, 0, buf.Length);
Console.WriteLine("Success");
string txt = Encoding.UTF8.GetString(buf);
Console.WriteLine(txt);
}
}
📝 비동기 호출
static void Main(string[] args)
{
AsyncPrint();
}
static async void AsyncPrint()
{
using (FileStream fs = new FileStream(@"C:\TestWorkspace\fileTest.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buf = new byte[fs.Length];
await fs.ReadAsync(buf, 0, buf.Length);
string txt = Encoding.UTF8.GetString(buf);
Console.WriteLine(txt);
}
}
📝 동기와 비동기의 쓰레드 차이
static void Main(string[] args)
{
Console.WriteLine("Before Call : "+ +Thread.CurrentThread.ManagedThreadId);
//SyncPrint();
AsyncPrint();
Console.WriteLine("After Call : " + +Thread.CurrentThread.ManagedThreadId);
}
static void SyncPrint()
{
using (FileStream fs = new FileStream(@"C:\TestWorkspace\fileTest.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buf = new byte[fs.Length];
Console.WriteLine("Before Sync Read : "+Thread.CurrentThread.ManagedThreadId);
fs.Read(buf, 0, buf.Length);
Console.WriteLine("After Sync Read : "+Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Success");
string txt = Encoding.UTF8.GetString(buf);
Console.WriteLine(txt);
}
}
static async void AsyncPrint()
{
using (FileStream fs = new FileStream(@"C:\TestWorkspace\fileTest.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buf = new byte[fs.Length];
Console.WriteLine("Before Sync Read : " + Thread.CurrentThread.ManagedThreadId);
await fs.ReadAsync(buf, 0, buf.Length);
Console.WriteLine("After Sync Read : " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Success");
string txt = Encoding.UTF8.GetString(buf);
Console.WriteLine(txt);
}
}
✅ SyncPrint 호출 시 결과
Before Call : 1
Before Sync Read : 1
After Sync Read : 1
Success
After Call : 1
✅ AsyncPrint 호출 시 결과
Before Call : 1
Before Sync Read : 1
After Call : 1
After Sync Read : 4
Success