【发布时间】:2013-08-12 16:50:37
【问题描述】:
在同时打开 Windows 窗体和控制台的 C# 应用程序中,为什么在关闭 From 时调用终结器,但在关闭控制台时不调用?即使从控制台关闭应用程序,是否有任何方法可以调用终结器?
我在创建一个在Construction上创建文件并在Dispose / Finalize上删除文件的类时注意到了这一点。关闭表单时它按预期工作,但关闭控制台时正在创建文件但未删除文件。
编辑
我一定对这些条款感到困惑。这是我的临时文件代码:
class TemporaryFile : IDisposable {
private String _FullPath;
public String FullPath {
get {
return _FullPath;
}
private set {
_FullPath = value;
}
}
public TemporaryFile() {
FullPath = NewTemporaryFilePath();
}
~TemporaryFile() {
Dispose(false);
}
private String NewTemporaryFilePath() {
const int TRY_TIMES = 5; // --- try 5 times to create a file
FileStream tempFile = null;
String tempPath = Path.GetTempPath();
String tempName = Path.GetTempFileName();
String fullFilePath = Path.Combine(tempPath, tempName);
try {
tempFile = System.IO.File.Create(fullFilePath);
break;
}
catch(Exception) { // --- might fail if file path is already in use.
return null;
}
}
String newTempFile = tempFile.Name;
tempFile.Close();
return newTempFile;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool calledFromDispose) {
DeleteFile();
}
public void DeleteFile() {
try {
System.IO.File.Delete(FullPath);
} catch(Exception) { } //Best effort.
}
}
【问题讨论】:
-
不要在 C# 中使用终结器。这是一个古老的概念。正确使用 IDisposable
-
没有示例代码/异常细节,这从未发生过......
-
你如何安排调用 Dispose() ?你做错了什么。
-
课程似乎没问题,我敢打赌你没有使用
using,也不要在你的应用程序中调用Dispose。您不能依赖终结器,它们完全有权不运行(尤其是在短期控制台应用程序中)。您必须使用Dispose(直接或通过using)。 -
@SoulDZIN - 您可以尝试禁用关闭按钮,以防止自己意外关闭它。 stackoverflow.com/questions/6052992/…
标签: c#