> > > An ugly solution would be to use GC.SuppressFinalize(fs).
Is there a better solution or good practice? (closing withot
flushing perhaps)?
I think you will have to use GC.SuppressFinalize(fs) after trying a
call to Dispose() or close() or using statement.
The FileStream's dispose (and IMO most "good" dispose methods) call
GC.SuppressFinalize at the end of the method call. However, because
of the exception, it is not getting called. So I wouldn't feel too
bad about manually supressing finalization.
I can't think of any other way to prevent an exception from being
raised on the Finalizer thread or catching that exception once thrown.
// a sample dispose function
void Dispose()
{
Dispose(true); // exception firing within this event...
GC.SuppressFinalize(this);
}
Although I do wonder if the file will continue to be locked since
Dispose was never called successfully. In the below program, it does
look like the file will be locked. Argh!
public static void Main ()
{
FileStream fs = new FileStream(@"A:\new.txt",
FileMode.Create);
bool diskfull = false;
try
{
while (true)
fs.WriteByte(0xff);
}
catch (IOException e)
{
Console.WriteLine("Exception: " + e.Message);
diskfull = true; // technically should only be set for
IOException when disk really is full.
}
finally
{
if (diskfull)
{
GC.SuppressFinalize(fs);
}
else
{
fs.Close();
}
}
// let's check to see if the file is locked.
try
{
using (FileStream fs1 = new FileStream(@"A:\new.txt",
FileMode.Open))
{
fs.ReadByte();
}
}
catch (Exception ex)
{
Console.WriteLine ("Exception: " + ex.Message);
}
Console.ReadLine();
}