C# hashtable example of caching online number of online users
Websites often need to cache the number of online users. Hashtable is a good choice. After all, access is very convenient and fast, and offline members can be deleted at any time to reduce the pressure on the server.
A static Hashtable must be defined, otherwise it cannot be cached; the "Hashtable.Synchronized" means that Hashtable is synchronized between processes to avoid errors. This class basically implements the methods to be used, just call it.
C# hashtable example of caching online number of online users
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web;
public class OnLineUser
{
private static Hashtable ht = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Add members to Hashtable
/// <summary>
/// <param name="userId">Member ID</param>
public static void AddUser(string userId)
{
if(!ht.Contains(userId))
ht[userId] = DateTime.Now;
}
/// <summary>
/// Check if the member is online
/// <summary>
/// <param name="userId">Member ID</param>
/// <param name="t">Do not request for more than a few minutes as offline</param>
/// <returns>true: online; false: not online</returns>
public static bool IsOnLineUser(string userId, int t)
{
if(ht.Contains(userId))
{
DateTime dt = (DateTime)ht[userId];
if(GetMinutes(DateTime.Now, dt) > t)
return true;
else
return false;
}
else
return false;
}
/// <summary>
/// Show all online members
/// <summary>
/// <returns>ll online members</returns>
public static string ShowOnLineUser()
{
if(ht.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach(DictionaryEntry de in ht)
sb += de.Value.ToSting();
}
return sb.ToSting();
}
/// <summary>
/// Take two time intervals(minutes)
/// </summary>
/// <param name="newTime">New time</param>
/// <param name="oldTime">Old time</param>
/// <returns>Two time intervals</returns>
public static int GetMinutes(DateTime dt1, DateTime dt2)
{
TimeSpan ts1 = new TimeSpan(dt1.Ticks);
TimeSpan ts2 = new TimeSpan(dt2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
return (int)ts.TotalMinutes;
}
}
-
Related Reading
- C# listview select row(a row and multiple rows)
- Solve the flickering problem of C# listview multithr
- C# convert punctuation marks to Unicode encoding
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- C# Winform button transparent background with proper
- Error cs1010 newline in constant - .net(C#) mislabel
- Convert Unicode to string C#(with string to unicode)
- C# Why does the generated random number repeat and g
- C# start exe with parameters(2 methods) and close ex
- C# set Winform icon and version number
- Mozilla Firefox cache location and change it in Wind