确定性资源清理
Coddy 面向 Ruby 开发者的 C# 课程的第 31 课,共 48 课。
Ruby 没有 using 语句。Ruby 的惯用写法是使用一个方法,将资源交给代码块处理,并在 ensure 子句中释放资源。向 File.open 传入代码块时,它就会这样做。C# using 会在作用域结束时调用 IDisposable.Dispose。即使异常导致代码块退出,这两种方式也都能确定性地清理资源。垃圾回收以及通过 ObjectSpace.define_finalizer 注册的 Ruby 终结器,运行时间都无法预测,因此不能替代这种清理方式。
IDisposable 通过 Dispose 提供确定性的清理。离开作用域时,using 语句会调用 Dispose,包括发生异常的情况。垃圾回收负责管理内存,但不能替代及时释放文件或其他资源。本课会模拟清理过程,不会接触真实文件。
Ruby 参考示例
class DemoScope
def self.open
scope = new
yield scope
ensure
scope.close if scope
end
def close
puts "closed"
end
end
DemoScope.open { |scope| puts "work" }C# 支持性声明
class DemoScope : IDisposable { public void Dispose() { Console.WriteLine("closed"); } }Main 中的 C# 语句
using (var scope = new DemoScope()) { Console.WriteLine("work"); }这些是用于教学的重点片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。
Ruby 输出:
work
closedC# 输出:
work
closed挑战
简单创建 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器