Search code examples
c#codefluent

Codefluent: Connections to the database remain after thread ends


If I run the code below, a lot of connections to the database remain doing nothing. You can check the number of open connections by running:

SELECT COUNT(dbid) as TotalConnections FROM sys.sysprocesses WHERE dbid > 0

Or, if you want more detail run the following command. You'll see a lot of connections with a 'AWAITING COMMAND' state:

sp_who2

I would have assumed that the Codefluent Persistency context would be gone after the thread exited and closed the connection. How can I force Codefluent to close the connection in the pool?

public void TestThreads()
{
    for (var i = 0; i < 1000; i++)
    {
        var t = new Thread(() => StaticticThreadContainer.Test());
        t.Start();
    }
}

public static int Test()
{
   var p = CwObject.LoadByEntityKey("baf04c09-7415-497d-b3cd-00004266f503");
   return 1;
 }

I found out a bit more. If I call the following code before returning in the thread the connection is closed properly. Is this the way to go?

CodeFluentContext.Get(Compareware.Constants.ApplicationStoreName).Persistence.ResetConnection(); 

Solution

  • Meziantou answered my question but the mentioned overload does not exist. The following code should do the trick:

    CodeFluent.Runtime.CodeFluentContext.GetExisting(Constants.MyStoreName)?.Persis‌​tence.ResetConnectio‌​n();
    CodeFluent.Runtime.CodeFluentContext.GetExisting(Constants.MyStoreName)?.Persistence.Dispose();