標籤:
public static class UserOnline{ /// <summary> /// 擷取或設定線上列表 /// </summary> public static Hashtable OnlineUserList { get { if (HttpContext.Current.Application["OnlineUserList"] == null) { Hashtable onlineUserList = new Hashtable(); HttpContext.Current.Application["OnlineUserList"] = onlineUserList; } return (Hashtable)HttpContext.Current.Application["OnlineUserList"]; } set { HttpContext.Current.Application["OnlineUserList"] = value; } } /// <summary> /// 添加線上成員 /// </summary> public static bool OnlineUserList_Add(string key, string value) { try { if (OnlineUserList.Contains(key)) OnlineUserList[key] = value; else OnlineUserList.Add(key, value); return true; } catch { return false; } } /// <summary> /// 添加線上成員 /// </summary> public static bool OnlineUserList_Add(string key) { string value = DateTime.Now.ToString(); return OnlineUserList_Add(key, value); } /// <summary> /// 離線刪除使用者 /// </summary> public static bool OnlineUserList_Delete(string key) { bool re = false; if (OnlineUserList.Contains(key)) { Hashtable userList = OnlineUserList; userList.Remove(key); OnlineUserList = userList; return true; } return re; } /// <summary> /// 判斷使用者是否線上 /// </summary> public static bool UserIsOnline(string adminName) { OnlineClearUserOutTimeInOnLineList(); return OnlineUserList.Contains(adminName) ? true : false; } /// <summary> /// 刪除逾時線上使用者 /// </summary> public static void OnlineClearUserOutTimeInOnLineList() { int OnlineTimeOut = 20; Hashtable list = new Hashtable(); Hashtable temList = new Hashtable(); list = OnlineUserList; temList = new Hashtable(list); foreach (DictionaryEntry de in temList) { //刪除逾時 DateTime onlineTime = Convert.ToDateTime(de.Value); TimeSpan timeSpan = DateTime.Now - onlineTime; //線上時間和目前時間間隔大於逾時分鐘數就刪除(註:使用者非法關閉瀏覽器) if (timeSpan.TotalMinutes >= (double)OnlineTimeOut) { list.Remove(de.Key); } } OnlineUserList = list; }}
ASP.NET C# 實現即時使用者線上