c# - Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anything? -
This seems like a very simple question, but I could not find a case of this special use after some searching .
Suppose I have a simple method, which says, determines whether a process has been opened by some file or not. I can do this (100% is not correct, but quite well) with this:
public bool isOpen (string fileName) {{file.Open (fileName, FileMode.Open , FileAccess., FileShare. Non); } Hold {// If an exception is thrown, then the file should be purchased by another process; }}
(Clearly it is not the best or the right way to determine - the file. Open opens many different exceptions, with all the different meanings , But it works for this example)
Now the file. Open
calls a file stream
, and the file stream
implies the IDisposable. Normally we want to wrap any FileStream
installation using any block in order to ensure that they are dealt with properly but what happens in this case where Do we really not give a return value to anything? Is it still necessary to settle FileStream
, like:
try {file.Open (fileName, FileMode.Open, FileAccess.Read, FileShare. as well)); {/ * Nop *}} hold {return true; }
Should I make a filestream
example and should resolve it?
try {use (filestream fs = File.Open (filename, filemodel, open file, read, fileshore non)); } ...
Or are they completely unnecessary? Do we just open open the file
Yes, you must definitly resolve FileStream
. Otherwise the stream will remain open and the file will not be used until it comes to final cleaning.
The important thing is to open ownership : for file
, the caller is considered "self" in the "back" stream - and if If you do something that implements IDisposable
, then it is your responsibility to settle it.
Compare this with the status of Image.FromStream
: In that case, you pass in a stream and Image
assumes that < Em> it owns the stream You should not not be in that situation, in that case - you have to settle the image when you do, and it will settle the stream.
The static method which gives some disposable almost always assumes that the caller takes ownership of the resources, which are the Detroit Constructors (which are effective methods in a steady way.)
In this case ironically, if you do not settle the stream returned by File.Open
, then you have found that the file is usable - it can also be used for some indefinite period She is making.
Comments
Post a Comment