Application error due to inaccessibility of FileStream

Before calling the Close () method of the FileStream object, I disconnect the main USB drive. The Close () method throws an exception when it tries to discard unwritten data. If I suppress the exception (catch, but do not throw it over), the finalizer is called an arbitrary amount of time later. He will try to clear the unwritten data, but he will encounter the same error, because of which the application will stop working.

Is there a standard way to handle a failed Close () call? It seems that if Close () encounters an error, you either 1) skip the file descriptor, or 2) make the application stop working, none of which is acceptable.

+4
source share
2 answers

If, instead of calling, Close()you call Dispose()or wrap your code in using, you can avoid the exception from the GC, since the finalizer will no longer try to destroy the stream.

+1
source

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

0
source

All Articles