在打开Windows窗体和控制台的C#应用程序中,为什么每当关闭From时调用Finalizer,而不是在控制台关闭时调用?即使从控制台关闭应用程序,有没有办法调用Finalizer?
我在创建一个在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.
}
}
Run Code Online (Sandbox Code Playgroud)