Menu
CoddyTech

确定性资源清理

Coddy 面向 C 开发者的 C# 课程的第 31 课,共 48 课。

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。仅当释放操作已执行时才返回 closed。完成资源的 Dispose 方法。重复调用两次也必须安全。

编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述行,调用 Exercise.Solve,验证输入未被修改,并在末尾输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。

锁定的启动程序还会独立测试导出的辅助函数或类 API,而不只是测试 Solve 包装函数。

亲手试试

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# 在线编译器