Menu
CoddyTech

결정적 리소스 정리

Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 31번째.

C에는 소멸자가 없습니다. 정리는 직접 작성하는 호출이며, 보통 goto cleanup 레이블을 통해 모든 종료 경로가 fclose 또는 free에 도달하도록 합니다. C#에서는 가비지 수집기가 메모리를 회수하므로 free는 없지만, 파일과 다른 리소스는 여전히 신속하게 해제해야 합니다. 형식은 IDisposable을 구현하며, using 블록은 예외를 포함한 모든 종료 경로에서 Dispose를 호출합니다. 이는 직접 작성한 정리 레이블을 대체합니다.

IDisposable은 Dispose를 통해 결정적인 정리를 제공합니다. using 문은 예외가 발생하는 경로를 포함해 범위를 벗어날 때 Dispose를 호출합니다. 가비지 수집은 메모리를 관리하지만 파일이나 다른 리소스를 신속하게 해제하는 일을 대신하지는 않습니다. 이 단원에서는 실제 파일을 건드리지 않고 정리를 구현합니다.

C 참조 코드

#include <stdio.h>

struct Scope { int open; };

static void scope_close(struct Scope *scope) {
    scope->open = 0;
    printf("closed\n");
}

static int process(int fail) {
    struct Scope scope = {1};
    int status = 0;
    if (fail) { status = -1; goto cleanup; }
    printf("work\n");
cleanup:
    scope_close(&scope);   /* 모든 종료 경로에서 반드시 여기에 도달해야 합니다 */
    return status;
}

int main(void) {
    process(0);
    process(1);
    return 0;
}

C# 보조 선언

class DemoScope : IDisposable { public void Dispose() { Console.WriteLine("closed"); } }

Main 안의 C# 문

using (var scope = new DemoScope()) { Console.WriteLine("work"); }

여기에는 핵심을 보여 주는 학습용 발췌 코드가 담겨 있습니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.

참조 출력:

work
closed
closed

C# 출력:

work
closed
challenge icon

챌린지

쉬움

TrackedResource를 만들고 using 블록에 진입하세요. fail이 true이면 InvalidOperationException을 던지고 포착하세요. Dispose가 실행된 경우에만 closed를 반환하세요. 리소스의 Dispose 메서드를 완성하세요. 두 번 호출해도 안전해야 합니다.

잠금 해제된 C# 파일을 수정하세요. 표시된 잠금 상태의 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 뒤 마지막에 개행 문자 하나를 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 인쇄하지 마세요.

잠금 상태의 실행기도 Solve 래퍼뿐만 아니라 내보낸 도우미 또는 클래스 API를 독립적으로 테스트합니다.

직접 해보기

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0] == "true"; string before0=Snapshot(a0);
var probeResource = new TrackedResource(); probeResource.Dispose(); probeResource.Dispose(); if (!probeResource.Disposed) throw new Exception("Dispose API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러