简单数据缓存类(c#)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
namespace WJ.Lib.Base
{
/// <summary>
/// DateBuffer 的摘要说明。
/// </summary>
public class DateBuffer
{
int mGetDateType; //数据类型
//object mobjBuffer;
string mSql;
SqlCommand mSqlCom;
DateTime mFlagDT; //上次更新时间
int mBufferTime; //更新时间间隔
Thread m_Thread; //超时时开启进程更新数据
DataTable mdtBuffer;
public DateBuffer()
{
mBufferTime = 2;
}
public DateBuffer(SqlCommand sSqlCom)
{
mBufferTime = 2;
mSqlCom = sSqlCom;
//从存储过程中获取数据
mGetDateType = 2;
}
public DateBuffer(string sSql)
{
mBufferTime = 2;
Sql = sSql;
//从查询语句中获取数据
mGetDateType = 1;
}
/// <summary>
/// 设置缓存时间(分钟)
/// </summary>
public int BufferTime
{
set
{
mBufferTime = value;
}
}
/// <summary>
/// 获取缓存数据
/// </summary>
public DataTable Buffer
{
get
{
CheckDate(true);
return mdtBuffer;
}
}
/// <summary>
/// 设置数据查询存储过程
/// </summary>
public SqlCommand SqlCom
{
set
{
if (mdtBuffer == null)
{
mdtBuffer = new DataTable();
}
mSqlCom = value;
//从存储过程中获取数据
mGetDateType = 2;
CheckDate(false);
}
get
{
return mSqlCom;
}
}
/// <summary>
/// 设置数据查询SQL
/// </summary>
public string Sql
{
set
{
if (mdtBuffer == null)
{
mdtBuffer = new DataTable();
}
mSql = value;
//从查询语句中获取数据
mGetDateType = 1;
CheckDate(false);
}
get
{
return mSql;
}
}
/// <summary>
/// 保持数据更新
/// </summary>
void CheckDate(bool CheckTime)
{
try
{
if (!CheckTime)
{
//需要立即更新数据
UpdateDate();
}
else if (mFlagDT < DateTime.Now)
{
//更新数据时间超时,采用线程更新数据
if(m_Thread == null
|| (m_Thread.ThreadState != System.Threading.ThreadState.Running
&& m_Thread.ThreadState != System.Threading.ThreadState.WaitSleepJoin ))
{
m_Thread = new Thread(new ThreadStart(UpdateDate));
m_Thread.Start();
}
}
}
catch
{
}
}
void UpdateDate()
{
DataTable dt = null;
try
{
if (mGetDateType == 1)
{
//通过查询语句获取表数据
dt = GetDateTable(mSql);
}
else if(mGetDateType == 2)
{
//通过存储过程获取表数据
dt =GetDateTable(ref mSqlCom);
}
mFlagDT = DateTime.Now.AddMinutes(mBufferTime);
}
catch
{
}
finally
{
if (dt != null)
{
mdtBuffer = dt;
}
}
}
}
}