C#

[C#] - 비동기 처리 : async 메소드가 아닌 경우 비동기 처리

Riucc 2019. 4. 9. 14:30

○ 비동기 처리 : async 메소드가 아닌 경우 비동기 처리

 

- 비동기 처리 : async 메소드가 아닌 경우 비동기 처리

     닷넷 BCL에 Async 메소드로 제공하지 않았던 모든 동기 방식의 메소드를 비동기로 변환가능

     사용자가 만드는 메소드에도 적용이 가능


      Task<TResult>로 바꾸면 await을 이용해 쉽게 비동기 호출을 할 수 있다

     이를 위해 ReadAllText 기능을 감싸는 비동기 버전의 메소드를 하나 더 만들면 된다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static Task<string> ReadAllTextAsync(string filepath)
{
        return Task.Factory.StartNew(() =>
        {
            // 텍스트 파일 불러올 시 한글 깨질 때, Encoind.Default 추가
            return File.ReadAllText(filepath, Encoding.Default);
        });
}
 
private static async void AwaitFileRead(string filePath)
{
        string fileTest = await ReadAllTextAsync(filePath);
        Console.WriteLine(fileTest);
}
 
AwaitFileRead(@"C:\Users\aa\source\repos\test0408\ConsoleApp3
\bin\Debug\testTxt.txt");
cs