In a C# application that opens both a Windows Form and a Console, how come the Finalizer is called whenever the From is closed, but not whenever the Console is closed? Is there any way for the Finalizer to be called even if the application is being closed from the console?
I noticed this when creating a class that creates a file on Construction and deletes the file on Dispose / Finalize. It worked as expected when closing the Form, but Files were being created but not removed when closing the Console.
EDIT
I must be confused about the terms. Here is my code for the Temporary File:
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.
}
}