using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Threading;
namespace Data
{
/// <summary>
/// LINQ数据库连接对象制造工厂
/// </summary>
static internal class DataContextFactory
{
static System.Timers.Timer sysTimer = new System.Timers.Timer(10000);
volatile static Dictionary<Thread, DataContext[]> divDataContext = new Dictionary<Thread, DataContext[]>();
static public int DataContextCount { get { return divDataContext.Count; } }
static DataContextFactory()
{
sysTimer.AutoReset = true;
sysTimer.Enabled = true;
sysTimer.Elapsed += new System.Timers.ElapsedEventHandler(sysTimer_Elapsed);
sysTimer.Start();
}
static void sysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
List<Thread> list = new List<Thread>();
foreach (Thread item in divDataContext.Keys)
{
if (item.ThreadState == ThreadState.Stopped)
{
list.Add(item);
}
}
for (int index = 0; index < list.Count; index++)
{
divDataContext.Remove(list[index]);
list[index] = null;
}
list = null;
}
/// <summary>
/// 通过工厂的制造模式获取相应的LINQ数据库连接对象
/// </summary>
/// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
/// <returns>LINQ数据库连接对象</returns>
public static DataContext Intance(string dbName)
{
return Intance(dbName, Thread.CurrentThread);
}
/// <summary>
/// 通过工厂的制造模式获取相应的LINQ数据库连接对象
/// </summary>
/// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
/// <param name="thread">当前线程引用的对象</param>
/// <returns>LINQ数据库连接对象</returns>
public static DataContext Intance(string dbName, Thread thread)
{
if (!divDataContext.Keys.Contains(thread))
{
divDataContext.Add(thread, new DataContext[4]);
}
if (dbName.Equals("zzl"))
{
if (divDataContext[thread][0] == null)
{
divDataContext[thread][0] = new Data.LinqzzlDataContext();
}
return divDataContext[thread][0];
}
else
{
return null;
}
}
}
}