在线人数统计

/// <summary>
/// OnLine 的摘要说明
/// </summary>
public class OnLine
{
private int OFFLINEDIFF;
private int REMOVEDIFF;


public OnLine()
{
///多少分钟不活动的用户从在线列表中删除
OFFLINEDIFF = 5;
///多少秒执行一次删除不活动用户
REMOVEDIFF = 30;

if (System.Web.HttpContext.Current.Application["DataTalbeOnline"] == null)
{
this.CashTableInit();
}
}

public void CheckOnline(string UserId,string UserName)
{
//从Application获取数据表、获取UserId
DataTable dtOnline;
dtOnline = (DataTable)System.Web.HttpContext.Current.Application["DataTalbeOnline"];

//数据表中是否有我的记录
DataRow drFind = dtOnline.Rows.Find(UserId);
if (drFind != null)
{
drFind["LastActiveTime"] = DateTime.Now;
}
else
{
DataRow drNew = dtOnline.NewRow();
drNew["UserId"] = UserId;
drNew["UserName"] = UserName;
drNew["LastActiveTime"] = DateTime.Now;
drNew["LoginTime"] = DateTime.Now;

dtOnline.Rows.Add(drNew);
}

//如果没有人正在执行删除且离上次删除的时间间隔超过设定值
TimeSpan tsRemove = DateTime.Now - Convert.ToDateTime(GetApplication("LastRemove"));
if (tsRemove.Seconds > REMOVEDIFF && this.GetApplication("Removing").ToString() == "n")
{
//锁定,我正在删除过期用户
System.Web.HttpContext.Current.Application.Lock();
SetApplication("Removing", "y");
System.Web.HttpContext.Current.Application.UnLock();
//不知道Rows.Count是否随循环减少,如果是效率就大于foreach且这里不能使用foreach
for (int i = 0; i < dtOnline.Rows.Count; i++)
{
DataRow drDel = dtOnline.Rows[i];
TimeSpan ts = DateTime.Now - Convert.ToDateTime(drDel["LastActiveTime"]);
if (ts.Minutes > OFFLINEDIFF)
{
dtOnline.Rows.Remove(drDel);
}
}

//我删完了,Response.Write("好累") ;
System.Web.HttpContext.Current.Application.Lock();
SetApplication("Removing", "n");
SetApplication("LastRemove", DateTime.Now.ToString());
System.Web.HttpContext.Current.Application.UnLock();
}

//把被我揉腻完了的数据表放回Application
dtOnline.AcceptChanges();
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["DataTalbeOnline"] = dtOnline;
System.Web.HttpContext.Current.Application.UnLock();
}
private string GetApplication(string apcname)
{
return System.Web.HttpContext.Current.Application[apcname].ToString();
}
public void SetApplication(string apcname, string apcvalue)
{
System.Web.HttpContext.Current.Application[apcname] = apcvalue;
}
/// <summary>
/// 创建表
/// </summary>
public void CashTableInit()
{
DataTable dt = new DataTable("OnlineTalbe");
dt.Columns.Add("UserId", typeof(string));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("LastActiveTime", typeof(DateTime));
dt.Columns.Add("LoginTime", typeof(DateTime));
dt.Columns["UserId"].Unique = true;
dt.PrimaryKey = new DataColumn[] { dt.Columns["UserId"] };

System.Web.HttpContext.Current.Application["DataTalbeOnline"] = dt;
System.Web.HttpContext.Current.Application["LastRemove"] = DateTime.Now.ToString();
System.Web.HttpContext.Current.Application["Removing"] = "n";
}
}

posted @ 2014-04-23 14:48  王者杂货铺  阅读(317)  评论(0编辑  收藏  举报