본문 바로가기

C#

2개의 스레드를 활용하여 압축 및 해제 작업을 동시에 수행하는 방법

반응형

C#으로 특정 폴더의 파일과 폴더를 압축하고 해제하는 프로그램을 만드는 과정을 설명해 드리겠습니다. 이 프로그램은 2개의 스레드를 활용하여 압축 및 해제 작업을 동시에 수행하도록 설계됩니다. 이렇게 하면 작업 효율성을 높일 수 있습니다.

1. 프로젝트 설정

먼저 Visual Studio에서 새 콘솔 애플리케이션 프로젝트를 생성합니다. 이 프로젝트에서는 System.IO.Compression 네임스페이스를 사용하여 파일을 압축하고 해제할 것입니다.

2. 필요한 네임스페이스 가져오기

압축과 스레딩을 위해 아래 네임스페이스를 가져옵니다.

using System;
using System.IO;
using System.IO.Compression;
using System.Threading;
 

3. 압축과 해제 작업을 위한 메서드 작성

두 가지 주요 작업을 수행할 메서드를 작성합니다. 첫 번째는 파일과 폴더를 압축하는 메서드이고, 두 번째는 압축을 해제하는 메서드입니다.

3.1 파일 및 폴더 압축 메서드

static void CompressFolder(string folderPath, string zipPath)
{
    try
    {
        if (Directory.Exists(folderPath))
        {
            ZipFile.CreateFromDirectory(folderPath, zipPath);
            Console.WriteLine("압축 완료: " + zipPath);
        }
        else
        {
            Console.WriteLine("폴더를 찾을 수 없습니다: " + folderPath);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("압축 중 오류 발생: " + ex.Message);
    }
}

3.2 파일 및 폴더 압축 해제 메서드

static void DecompressFolder(string zipPath, string extractPath)
{
    try
    {
        if (File.Exists(zipPath))
        {
            ZipFile.ExtractToDirectory(zipPath, extractPath);
            Console.WriteLine("압축 해제 완료: " + extractPath);
        }
        else
        {
            Console.WriteLine("압축 파일을 찾을 수 없습니다: " + zipPath);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("압축 해제 중 오류 발생: " + ex.Message);
    }
}

4. 스레드를 이용한 병렬 작업

두 가지 작업을 동시에 수행하기 위해 각각의 작업을 별도의 스레드에서 실행합니다.

4.1 메인 메서드 작성

static void Main(string[] args)
{
    string folderToCompress = @"C:\ExampleFolder";
    string zipFilePath = @"C:\ExampleFolder.zip";
    string extractFolderPath = @"C:\ExtractedFolder";

    // 압축 스레드 생성
    Thread compressThread = new Thread(() => CompressFolder(folderToCompress, zipFilePath));
    // 압축 해제 스레드 생성
    Thread decompressThread = new Thread(() => DecompressFolder(zipFilePath, extractFolderPath));

    // 스레드 시작
    compressThread.Start();
    decompressThread.Start();

    // 스레드가 작업을 완료할 때까지 대기
    compressThread.Join();
    decompressThread.Join();

    Console.WriteLine("모든 작업이 완료되었습니다.");
}

5. 프로그램 실행

프로그램을 실행하면 다음과 같은 순서로 진행됩니다:

  1. CompressFolder 메서드가 실행되어 지정한 폴더를 압축합니다.
  2. 동시에 DecompressFolder 메서드가 실행되어 압축 파일을 해제합니다.

각 작업은 별도의 스레드에서 병렬로 수행되므로 작업 효율이 향상됩니다.

6. 마무리

이번 블로그에서는 C#으로 특정 폴더를 압축하고 해제하는 프로그램을 만들었습니다. 이 프로그램은 System.IO.Compression 네임스페이스를 활용하였으며, 스레드를 사용하여 동시에 압축과 해제 작업을 수행하도록 구현했습니다. 이를 통해 파일 처리 작업을 더욱 효율적으로 관리할 수 있습니다.

반응형