asp.net 中的守护线程.定时器

使用单例和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();
                }

            }
        }    
    }
     
   }


    
    
   
   
  
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值