Dan
Dan

Reputation: 1243

App crash due to uncloseable FileStream

Just prior to calling the Close() method on a FileStream object, I unplug the underlying USB drive. The Close() method will throw an exception when it attempts to flush unwritten data. If I squelch the exception (catch, but don't re-throw) the finalizer is invoked an arbitrary amount of time later. It will attempt to flush unwritten data but encounters the same error, causing the application to terminate.

Is there a standard way to handle a failing Close() invocation? It seems that if Close() encounters an error you either 1) leak a file handle or 2) cause the application to terminate, neither of which is acceptable.

Upvotes: 4

Views: 197

Answers (2)

ths
ths

Reputation: 2942

if instead of calling Close(), you call Dispose(), or wrap your code in a using, you should be able to avoid the exception from GC, since the finalizer will not try to dispose the stream anymore.

Upvotes: 1

Alecu
Alecu

Reputation: 2708

You can use GC.SuppressFinalize to suppress the finalizer from executing so later when the object is garbage collected you will not get an error.

Upvotes: 0

Related Questions