c# - Why is calling Dispose() in a finalizer causing an ObjectDisposedException? -


i have nhibernate repository looks this:

public class nhibrepository : idisposable {     public isession session { get; set; }     public itransaction transaction { get; set; }      // constructor     public nhibrepository()     {         session = database.opensession();     }      public iqueryable<t> getall<t>()     {         transaction = session.begintransaction();         return session.query<t>();     }      public void dispose()     {         if (transaction != null && transaction.isactive)         {             transaction.rollback(); // objectdisposedexception on line         }          session.close();         session.dispose();     }      ~nhibrepository()     {         dispose();     } } 

when use repository this, runs fine:

using (var repo = new nhibrepository()) {     console.writeline(repo.getall<product>().count()); } 

but when use this, throw objectdisposedexception:

var repo = new nhibrepository(); console.writeline(repo.getall<product>().count()); 

the easy solution dipose of repository explicitly, unfortunately don't control life cycle of of classes use repository.

my question is, why transaction disposed of though did not explicitly call dispose()? i'd have repository automatically clean if not disposed explicitly.

my question is, why transaction disposed of though did not explicitly call dispose()?

perhaps transaction's finalizer ran first. remember, finalizers of dead objects can run in order , on thread, , need not have been correctly initialized before finalized. if not understand all rules of finalizers learn them before attempt write more code uses finalizers. 1 of hardest things right.

it looks though have implemented disposable pattern incorrectly, , going cause world of grief. read on pattern , correctly; finalizer should not disposing stuff has been disposed:

http://msdn.microsoft.com/en-us/magazine/cc163392.aspx


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -