62,072
社区成员
发帖
与我相关
我的任务
分享
//DAL.CacheData.cs
namespace DAL
{
public class CacheData
{
private string _source;
///<summary>
///指示数据从何而来
///</summary>
public string Source
{
set { _source = value; }
get { return _source; } }
public CacheData()
{
_source = "未知类型";
}
///<summary>
///从缓存中获取数据
///</summary>
public DataSet GetDataFromCache()
{
string cacheKey = ConfigurationManager.AppSettings["TCM_sys_user"].ToString();
string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
//SqlCacheDependencyAdmin.EnableNotifications(connString);
if (HttpRuntime.Cache[cacheKey] != null)
{ _source = "从缓存中取得";
return (DataSet)HttpRuntime.Cache[cacheKey];
}
else
{
SqlDependency.Start(connString);
DataSet ds = new DataSet();
string sqlGetAllUser = "select * from sys_user";
using (SqlConnection conn = new SqlConnection(connString))
{ //SqlDataAdapter da = new SqlDataAdapter(cmd);
// DataSet ds = new DataSet();
// da.Fill(ds);
// DataView dv = ds.Tables[0].DefaultView;
using (SqlCommand cmd = new SqlCommand(sqlGetAllUser, conn))
{
SqlCacheDependency dependency = new SqlCacheDependency(cmd);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
//SqlDependency.Start(connString);
da.Fill(ds);
}
HttpRuntime.Cache.Insert(cacheKey, ds, dependency,DateTime.Now.AddMinutes(30), TimeSpan.Zero);
}
}
_source = "从表中取得";
return ds;
}
}
}
}
//sqlcachedependency.sqldependency.aspx
namespace sqlcachedependency
{
public partial class sqldependency : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DAL.CacheData cacheData = new DAL.CacheData();
gvShowUser.DataSource = cacheData.GetDataFromCache();
gvShowUser.DataBind();
lbl_source.Text = cacheData.Source;
HyperLink1.NavigateUrl = "index.aspx";
}
}
}
//sqlcachedependency.Global.asax
namespace sqlcachedependency
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
SqlDependency.Start(connString);
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
SqlDependency.Stop(connString);
}
}
}