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

C# Task 비동기 API 예제

by HyunS_ 2019. 6. 8.
using System;
using System.IO;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
           if(args.Length < 2)
           {
                Console.WriteLine("Usage: AsyncFileIO <Source> <Destination>");
                return;
           }

           DoCopy(args[0], args[1]);

           Console.ReadLine();
        }

        static async Task<long> CopyAsync(string fromPath, string toPath)
        {
            using(var fromStream = new FileStream(fromPath, FileMode.Open))
            {
                long totalCopied = 0;

                using(var toStream = new FileStream(toPath, FileMode.Create))
                {
                    byte[] buffer = new byte[1024];
                    int nRead = 0;
                    while((nRead = await fromStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        await toStream.WriteAsync(buffer, 0, nRead);
                        totalCopied += nRead;
                    }
                }

                return totalCopied;
            }
        }

        static async void DoCopy(string fromPath, string toPath)
        {
            long totalCopied = await CopyAsync(fromPath, toPath);
            Console.WriteLine($"Copied total {totalCopied} Bytes");
        }
    }
}
728x90

댓글