使用单例和static的相关知识,自己搞了一个定时器..
主要是定时执行某项功能用..
而且只有一个的守护线程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
namespace ZGL.Session
{
public class MySessionContext
{
///
/// 自动销毁过期Session的线程
///
private static Thread _AutoDestroyTimeOutSessionThread;
///
/// 销毁超时Session的方法
///
private static void DestroyTimeOutSession()
{
//1.查找过时的Seesion
Dictionary
SessionPools = MySessionContext.SessionPools;
while (true) //无限循环
{
Thread.Sleep(60000);//挂起1分钟后再执行
DateTime now = DateTime.Now;
//1.查找过时的Seesion //20分钟的过期时间
var oldSessions = SessionPools.Where(session => (now - session.Value.LastUpdateTime).Minutes > 20)
.Select(p=>p.Key).ToArray();
//2.销毁
foreach (var item in oldSessions)
{
SessionPools.Remove(item);
}
}
}
///
/// 保存在服务端的Session池,单例且唯一
///
///
/// Dictionary
///
public static readonly Dictionary
SessionPools = new Dictionary
();
///
/// 取得当前Http请求所对应的MySession,如果本来没有MySession则会自动创建一个MySession.
///
public static MySession CurrentSession
{
get
{
HttpContext context = HttpContext.Current;
MySession mySession = null;
string SessionId = null;
//创建超时守护线程.
if (_AutoDestroyTimeOutSessionThread == null)
{
_AutoDestroyTimeOutSessionThread = new Thread(DestroyTimeOutSession);
_AutoDestroyTimeOutSessionThread.Start();
}
}
}
}
}