V
Volker Hetzer
Hi!
I've got a file container that, upon disposing, might try to write to a file.
Now, I want to tie the lifetime of that file to the lifetime of some object which also uses the container:
public class myFileObject
{
myFileObject()
{
_FileName=Path.GetTempFileName();
_FHC=new FileHandlingContainer(_FileName);
}
public void workWithFHC(Params)
{
_FHC.MethodInvocation(Params);
}
private FileHandlingContainer _FHC;
private string _FileName;
}
How would I now implement a Disposable Interface and a Finalizer?
The Problem I'm facing is that I need to guarantee that the file
gets deleted after _FHC is disposed. If not, then either I try to
delete an open file or _FHC tries to write to a deleted file.
The normal Dispose Pattern says that
- Dispose(true) should Dispose of _FHC and the file behind _FileName
- Dispose(false) only the file and
- ~myFileObject() should call Dispose(false)
But if the caller forgets using "using", the finalizer might delete the file
before _FHC has been disposed, right?
So, either "using" or the Garbage collector need to guarantee that _FHC
is dead before myFileObject deletes the file.
Does anyone have any idea? In C++ I'd use an auto_ptr<myFileObject> and do
the rest in the destructor but I have no idea how to do that in C#.
Lots of Greetings!
Volker
I've got a file container that, upon disposing, might try to write to a file.
Now, I want to tie the lifetime of that file to the lifetime of some object which also uses the container:
public class myFileObject
{
myFileObject()
{
_FileName=Path.GetTempFileName();
_FHC=new FileHandlingContainer(_FileName);
}
public void workWithFHC(Params)
{
_FHC.MethodInvocation(Params);
}
private FileHandlingContainer _FHC;
private string _FileName;
}
How would I now implement a Disposable Interface and a Finalizer?
The Problem I'm facing is that I need to guarantee that the file
gets deleted after _FHC is disposed. If not, then either I try to
delete an open file or _FHC tries to write to a deleted file.
The normal Dispose Pattern says that
- Dispose(true) should Dispose of _FHC and the file behind _FileName
- Dispose(false) only the file and
- ~myFileObject() should call Dispose(false)
But if the caller forgets using "using", the finalizer might delete the file
before _FHC has been disposed, right?
So, either "using" or the Garbage collector need to guarantee that _FHC
is dead before myFileObject deletes the file.
Does anyone have any idea? In C++ I'd use an auto_ptr<myFileObject> and do
the rest in the destructor but I have no idea how to do that in C#.
Lots of Greetings!
Volker