none
Disposing of a shared resource RRS feed

  • Question

  • Hi,

    Im building a base class for all our business classes to inherit.  The classes will include the data layer, and therefore use a connection and in some cases a transaction.

    I would like to pass in the connection to the class, and then normal expect the classes dispose routine to clean the connection up.  However there is the case were I would like more than one class instance to share the same connection, (and transaction) so that I could ensure when the classes save, its an all or nothing situation. etc.

    In which case i wont want to dispose of the connection if one of the classes disposes, whilst the another class (thats using the same connection) is still in use.

    Does anyone know of a tidy way of dealing with this.  I'm relatively new to dotnet.

    Thanks

    Tuesday, August 19, 2008 9:05 AM

Answers

  • You would have to implement some reference counting scheme where each client that uses the connection object increments the count and the Dispose() method decrements the count.  Call the connection object's Dispose() method when the count reaches zero.  Once you start to contemplate schemes like this, it starts to make sense to just let the garbage collector take care of releasing the resources with the finalizer.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, August 25, 2008 7:59 AM
    Tuesday, August 19, 2008 11:48 AM
    Moderator

All replies

  • You would have to implement some reference counting scheme where each client that uses the connection object increments the count and the Dispose() method decrements the count.  Call the connection object's Dispose() method when the count reaches zero.  Once you start to contemplate schemes like this, it starts to make sense to just let the garbage collector take care of releasing the resources with the finalizer.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, August 25, 2008 7:59 AM
    Tuesday, August 19, 2008 11:48 AM
    Moderator
  • Thanks for the advice, I agree reference counting is over kill to say the least.  I'll implement so that it only disposes the connection and trans if I'm not manually controlling the connection & transaction. 

    Tuesday, August 19, 2008 1:19 PM