Thursday, August 1, 2013

Connection Pooling and connection leak

Please post using CodeBlock function, it makes the code a whole ton more readable:



using (var context = GetMyEntityConnection())
{
//Do Stuff
var myRecord = context.MyTable.Where(x=> x.id == 1).SingleOrDefault();
//Do more stuff
}

protected MyEntities GetMyEntityConnection()
{
var context = new MyEntities(GetPreparedConnection(FSWellKnownConnection.MyDB));
context.CommandTimeout = Constants.ENTITY_CONNECTION_TIMEOUT;
return context;
}

public virtual EntityConnection GetPreparedConnection(FSWellKnownConnection connection)
{
EntityConnection con = null;
try
{
con = new EntityConnection(GetConnectionString(connection));
con.Open();
using (var com = con.StoreConnection.CreateCommand())
{
com.CommandType = System.Data.CommandType.Text;
com.CommandText = "set arithabort on;";
com.ExecuteNonQuery();
}
}
catch
{
if (con != null)
{
con.Dispose();
con = null;
}
throw;
}
return con;
}

The first piece of code kinda stands in open space.


You Implement Dispose for one of two reasons:


1. You handle Umanaged Resources. Then you should also deal with Finalizing too. A rather uncommon case.


2. You handle one or more class instances that deal with umanaged resources, also Called "Basic Dispose Pattern". Then all you should do is is call the contained classes Dispose(). Leave Finalizing alone (that is a matter between the isntance and the GC, and only those two).


This article deals with Dispose/Finalize pattern (and how to avoid repetiton of code):


http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx


"MyEntities" class looks userwritten, so we have no idea if it follows rule two properly.


On the other hand it sounds like the connectiosn times out. It is a rather atypical behavior for failed disposing - either the Connection is Closed (wich includes waiting for the partner to recognise the Closure), or the Connection Instance will stay in memory and continue to communicate indeffinitely (until it's Finalizer is called by the GC). Though there could be a 5 minute "inactivity" counter on the server side, just in case you forget to dispose.




Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


No comments:

Post a Comment