본문 바로가기
C#/책 예제

C# Task ReadAllText 메서드를 비동기로 처리하기.

by HyunS_ 2019. 6. 9.
728x90

ReadAllText 메서드를 비동기로 처리하기 입니다.

 

별도의 스레드를 이용하거나 델리게이트의 BeginInvoke로 처리하여 비동기를 적용하는 예제입니다.(복잡함)

using System;
using System.IO;

namespace TaskSample
{
    class Program
    {
        public delegate string ReadAllTextDelegate(string path);

        static void Main(string[] args)
        {
            string filePath = @"C:\windows\system32\drivers\etc\HOSTS";

            ReadAllTextDelegate func = File.ReadAllText;
            func.BeginInvoke(filePath, actionCompleted, func);

            Console.ReadLine();
        }

        static void actionCompleted(IAsyncResult asyncResult)
        {
            ReadAllTextDelegate func = asyncResult.AsyncState as ReadAllTextDelegate;
            string fileText = func.EndInvoke(asyncResult);

            Console.WriteLine(fileText);
        }
    }
}


위의 예제를 Task<TResult>로 바꾸면 await을 이용하여 쉽게 비동기 호출을 적용할 수 있습니다.

 

Async 메서드로 제공되지 않은 모든 동기 방식의 메서드를 비동기로 변환 가능합니다.

using System;
using System.IO;
using System.Threading.Tasks;

namespace TaskSample
{
    class Program
    {
        public delegate string ReadAllTextDelegate(string path);

        static void Main(string[] args)
        {
            string filePath = @"C:\windows\system32\drivers\etc\HOSTS";

            AwaitFileRead(filePath);

            Console.ReadLine();
        }

        static Task<string> ReadAllTextAsync(string filePath)
        {
            return Task.Factory.StartNew(() =>
            {
                return File.ReadAllText(filePath);
            });
        }

        private static async Task AwaitFileRead(string filePath)
        {
            string fileText = await ReadAllTextAsync(filePath);

            Console.WriteLine(fileText);
        }
    }
}

 

728x90

댓글