Strange(?) behaviour of SqlCeConnection

A

Adam

Hello, I observe a strange behaviour of SqlCeConnection disposing.
I have a simple class to connect to DB with one static SqlCeConnection

namespace SOMETHING
{
/// <summary>
/// This singleton class holds the common application values.
/// </summary>
sealed class Common : IDisposable
{
// Singleton instance variable (Values)
public static readonly Common Values = new Common();

private Common()
{
Load();
}

public void Load()
{
this.databaseConnection = new
SqlCeConnection(LocalConnectionString);

}

public void DbOpen()
{
if (this.databaseConnection.State != ConnectionState.Open)
this.databaseConnection.Open();
}

#region Properties
private SqlCeConnection databaseConnection;
public SqlCeConnection DatabaseConnection
{
get { return databaseConnection; }
set { databaseConnection = value; }
}

public string LocalConnectionString
{
get { return "Data Source=" + localDbPath + localDbName + ";
Password = test"; }
}

public string AppPath
{
get { return
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}
}
#endregion

#region Dispose
public void Dispose()
{
if(this.databaseConnection.State != ConnectionState.Closed)
this.databaseConnection.Close();
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
//czy zapisywac zmiany przy usuwaniu obiektu?
//Save();
}
#endregion

~Common()
{
//Dispose();
}
}
}


and from Form1.cs code I do

Common.Values.DbOpen();

in Form1 on load event
and

Common.Values.Dispose();

in Form1 closing event
and everything is ok. But when I uncomment Dispose in Common destructor and
not use Common.Values.Dispose() in Form1 closing event application hang on
this.databaseConnection.Close() in Dispose function. Why?
 
G

Guest

This looks as if you have somekind of locking problem I would guess. To be
honest I wouldn't implement a Finalizer in this case. If you were to call
Dispose from your client app, you might have a synchronization issue.
Consider the following: You call Dispose, then the object becomes eligible
for clean up, so the GC calls your Finalizer, you now have two threads in
your Dispose method. This is very unlikely because the timing would have to
be just right. If you still want a Finalizer, consider calling
GC.SuppressFinalize(this) in your dispose method to limit a double clean up.

I would recomend using the *using* statement and keep the Dispose method.
Once control leaves the using statement the Dispose method is called for you.
To to this though, you'd of course have to loose the singleton pattern!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top