In my multi threaded windows service I open connections to the db on each thread, after that I dispose those connections, though the problem is that some are left not closed on the db when I perform query on the sys.sysprocesses table.
I ran two unit tests and saw some weird behavior, in first I ran a loop with 100 tasks, and in everyone of them I open a new connection. After these are finished (I see via WaitAll()) I see that some connections are still hanging in the db. On second unit test, when I run several open/dispose without parallel execution, it disposes them just fine and there are no hanging connections in my db.
The problem is that in my Windows Service, these hanging connections are being added up and in the end there is no more place for new connections and db becomes not usable for the user.
Here are the codes, first is parallel, second is not:
[TestMethod]
public void TestMultiThreadedAccessToExplicitObjectContext()
{
int taskSize = 100;
List<Task> taskList = new List<Task>();
int goodSources = 0;
for (int i = 0; i < taskSize; i++)
{
Task newTask = Task.Factory.StartNew(() =>
{
System.Data.Objects.ObjectContext objectContext = new PersoniteEntities();
objectContext.Connection.Open();
objectContext.Dispose();
Thread.Sleep(1200);
});
taskList.Add(newTask);
}
Task.WaitAll(taskList.ToArray());
GC.Collect();
total += goodSources;
}
[TestMethod]
public void TestMultiThreadedAccessToExplicitObjectContextInline()
{
System.Data.Objects.ObjectContext objectContext1 = new PersoniteEntities();
objectContext1.Connection.Open();
objectContext1.Dispose();
System.Data.Objects.ObjectContext objectContext2 = new PersoniteEntities();
objectContext2.Connection.Open();
objectContext2.Dispose();
System.Data.Objects.ObjectContext objectContext3 = new PersoniteEntities();
objectContext3.Connection.Open();
objectContext3.Dispose();
System.Data.Objects.ObjectContext objectContext4 = new PersoniteEntities();
objectContext4.Connection.Open();
objectContext4.Dispose();
System.Data.Objects.ObjectContext objectContext5 = new PersoniteEntities();
objectContext5.Connection.Open();
objectContext5.Dispose();
}
Thanks