728x90
반응형
728x170
▶ Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace TestProject
{
/// <summary>
/// 프로그램
/// </summary>
class Program
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Private
#region 프로그램 시작하기 - Main()
/// <summary>
/// 프로그램 시작하기
/// </summary>
private static void Main()
{
string[] argumentArray = Environment.GetCommandLineArgs();
if(argumentArray.Length > 1)
{
List<Task<long>> taskList = new List<Task<long>>();
for(int i = 1; i < argumentArray.Length; i++)
{
taskList.Add(GetDirectorySizeAsync(argumentArray[i]));
}
try
{
Task.WaitAll(taskList.ToArray());
}
catch(AggregateException)
{
}
for(int i = 0 ; i < taskList.Count; i++)
{
if(taskList[i].Status == TaskStatus.Faulted)
{
Console.WriteLine($"{argumentArray[i + 1]} 디렉토리가 없습니다.");
}
else
{
Console.WriteLine($"{argumentArray[i + 1]} 디렉토리 크기 : {taskList[i].Result:N0} 바이트");
}
}
}
else
{
Console.WriteLine("구문 에러 : 1개 이상의 디렉토리 경로를 지정해 주시기 바랍니다.");
}
}
#endregion
#region 디렉토리 크기 구하기 (비동기) - GetDirectorySizeAsync(directoryPath)
/// <summary>
/// 디렉토리 크기 구하기 (비동기)
/// </summary>
/// <param name="directoryPath">디렉토리 경로</param>
/// <returns>디렉토리 크기</returns>
private static Task<long> GetDirectorySizeAsync(string directoryPath)
{
if(!Directory.Exists(directoryPath))
{
return Task.FromException<long>(new DirectoryNotFoundException("디렉토리가 없습니다."));
}
else
{
string[] filePathArray = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
if(filePathArray.Length == 0)
{
return Task.FromResult(0L);
}
else
{
return Task.Run
(
() =>
{
long totalFileLength = 0;
Parallel.ForEach
(
filePathArray,
(filePath) =>
{
FileStream fileStream = new FileStream
(
filePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite,
256,
true
);
long fileLength = fileStream.Length;
Interlocked.Add(ref totalFileLength, fileLength);
fileStream.Close();
}
);
return totalFileLength;
}
);
}
}
}
#endregion
}
}
728x90
반응형
그리드형(광고전용)
'C# > TPL' 카테고리의 다른 글
[C#/TPL] Task 클래스 : WhenAll 정적 메소드 사용하기 (0) | 2021.06.27 |
---|---|
[C#/TPL] Task 클래스 : CompletedTask 속성 사용하기 (0) | 2021.06.26 |
[C#/TPL] Task 클래스 : FromException 메소드 사용하기 (0) | 2021.06.26 |
[C#/TPL] Task 클래스 : FromCanceled<T> 정적 메소드 사용하기 (0) | 2021.06.26 |
[C#/TPL] Task 클래스 : FromException<T>/FromResult<T> 정적 메소드 사용하기 (0) | 2021.06.26 |
[C#/TPL] Parallel 클래스 : ForEach 정적 메소드를 사용해 디렉토리 크기 구하기 (0) | 2021.06.26 |
[C#/TPL] 누겟 설치 : System.Threading.Tasks.Dataflow (0) | 2021.06.26 |
[C#/TPL] Task 클래스 : 일정 주기 반복 태스크 시작하기 (0) | 2021.01.09 |
[C#/TPL] Task 클래스 : 태스크 완료시/에러시 처리하기 (0) | 2020.08.17 |
[C#/TPL] Task<T> 클래스 : 변환 함수를 사용해 비동기 변환하기 (0) | 2019.11.24 |
[C#/TPL] 함수형 확장 사용하기 (0) | 2019.11.23 |
댓글을 달아 주세요