"Koliber (js)" <(E-Mail Removed)> schrieb im Newsbeitrag
news:91b9bc15-e359-4069-b533-(E-Mail Removed)...
>I feel i still do not understand maybe a bit a dispose pattern
> So I have a question - is this code right? Is fs.Close() there where
> it is right?
> If I do understand it in place 'BBB' there can be a situation where
> such member
> obiect as fs can be finalised - so it may be wrong. Am I right or not?
> But if i would close fs in place 'AAA' then I am not sure if a user of
> this class
> called a dispose() on it ? Am I wrong or right?
>
> Thanks for Answer
> JS
>
>
>
> class JpgFileDecoder : IDisposable
> {
> private FileStream fs = null;
<snip>
>
> private bool isDisposed = false;
>
> public JpgFileDecoder(string filePath,
> ProgressEventHandler progressEventHandler)
> {
> this.progressEventHandler = progressEventHandler;
> fs = new FileStream(filePath, FileMode.Open,
> FileAccess.Read);
> fs.Seek(0, SeekOrigin.Begin);
You shouldn't open your filestream an the get-accessor. If this property is
assigned twice, the former filestream remains open. Also calling programmers
wouldn't expect the object to enter open state on property-assignment.
Better is an Open method.
> }
>
>
> ~JpgFileDecoder()
> {
> Dispose(false);
> }
Actually it's not needed here, to have a finalizer, because you don't have
any unmanaged resources. It will raise performance issues (though maybe
small.)
This pattern can be handy, if a deriving class will reference unmanaged
resources directly, but maybe it is better to make your class sealed.
>
> protected void Dispose(bool disposing)
> {
> if (disposing)
> {
> // AAA
> // Code to dispose the managed resources of the class
>
> }
> //BBB
> // Code to dispose the un-managed resources of the
> class
>
> fs.Close();
> fs = null;
fs is a managed resource (=~ managed class that implements IDisposable). So
this should appear under // AAA.
So far
Christof Nordiek
>
> //
>
> isDisposed = true;
> }
>
> public void Dispose()
> {
> Dispose(true);
> GC.SuppressFinalize(this);
> }
> }
|