Menu
CoddyTech

결정론적 리소스 정리

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

C++의 RAII는 범위를 벗어날 때 결정론적으로 소멸자를 실행합니다. C#의 관리 객체 메모리는 가비지 컬렉션을 사용하므로, 리소스를 결정론적으로 정리하는 대신 using과 IDisposable을 사용합니다. C#의 종료자는 C++의 스택 소멸자를 직접 대체하지 않습니다.

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

C++ 참고 코드

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class TrackedResource { bool& disposed; public: explicit TrackedResource(bool& value):disposed(value) {} ~TrackedResource() { disposed=true; } };
int main() {
bool disposed=false;
{ TrackedResource resource(disposed); }
cout << (disposed?"closed":"open") << "\n";
}

C# 지원 선언

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

Main 내부의 C# 문

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

이 내용은 핵심 개념을 설명하기 위한 발췌문입니다. 과제 파일에는 실행 가능한 완전한 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.

참고 출력:

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# 컴파일러