0

Although I am aware of the working of both finally and finalizer I have a clarification which needs to be cleared .

I have a situation where I am opening a connection to Datbabase instance and performing operations. Like

try 
{
  //Open a connection to db
  //Perform some operations.
}
catch(Exception e)
{
}
finally
{
 //Call the dispose method
}

Here I know that finally will be called all the time so the dispose will happen every single time.

Next ,in the finalizer I dispose the connection.

public class DbConnection
{

  ~DbConnection()
   {
     //Call the dispose method
   }

}.

The same operation , is being performed by both the methods i.e., release unmanaged resources . Although there is problem sometimes with finalizer , like "Handler closed by finalizer before it is being accessed" , then why would I go with finalizer? In this scenario is it feasible to go with finally approach for my situation?

user1400915
  • 1,933
  • 6
  • 29
  • 55
  • 4
    personally i avoid using a finalizer, because depending on your program you may not be sure when it is called by the GC. – Sebastian L May 24 '17 at 07:24
  • just refer to this documentation [enter link description here](https://stackoverflow.com/questions/27815947/difference-between-final-keyword-finally-block-and-finalized-method-in-java-thr) – DotNetLover May 24 '17 at 07:24
  • That is Java @DotNetLover – Patrick Hofman May 24 '17 at 07:25
  • 1
    [This should cover it](https://stackoverflow.com/questions/13988334/difference-between-destructor-dispose-and-finalize-method) – ProgrammingLlama May 24 '17 at 07:25
  • 2
    If you have an instance of `IDisposable` than you should also call `Dispose` in a timely manner where you know when this happens. This is best and most safely done with a `using`-statement. – MakePeaceGreatAgain May 24 '17 at 07:26
  • Take notice of the answer of Marc in the duplicate. He explains it very well why you should prefer `IDisposable` over finalizers. – Patrick Hofman May 24 '17 at 07:27
  • You could [read here](https://stackoverflow.com/a/4088544/2846483) about finalizers "and how to eat them". – dymanoid May 24 '17 at 07:28

0 Answers0