我正在构建一个MVC应用程序,它需要每2分钟从DB中获取更新的数据,我正在考虑在每个会话中使用Timer,它将每2分钟调用SP,并使用SignleR更新客户端,我担心的是每次会话都要保持Timer这个应用程序将支持10000个用户同时我很乐意得到一些建议感谢
每个进程而不是每个会话都应该有一个Timer,每次它启动并获得DB数据时,它都会决定是否应该进行SignalR广播/组/个人连接。
如何构建一个在应用程序生命周期中持续存在的单个计时器:
public static class SessionTimer
{
static _timer = new System.Timers.Timer();
static List<Action> _delegates = new List<Action>();
static Dictionary<string, Action> _delegateLookup = new Dictionary<string, Action>();
static object _lockObj = new Object();
static SessionTimer()
{
_timer.Interval = 120000;
_timer.Elapsed
_timer.Start();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
foreach (var d in _delegates)
{
d();
}
}
public static Enlist(HttpSessionState s, Action d)
{
lock (_lockObj)
{
_delegates.Add(d);
_delegateLookup.Add(s.SessionID, d);
}
}
public static Delist(HttpSessionState s)
{
lock (_lockObj)
{
_delegates.Remove(_delegateLookup[s.SessionID]);
_delegateLookup.Remove(s.SessionID);
}
}
}
现在,您所要做的就是在会话开始时登记会话。您可以在Global.asax
中获取Session_Start
处理程序来执行此操作:
void Session_Start(object sender, EventArgs e)
{
SessionTimer.Enlist(HttpContext.Current.Session, someActionHandler);
}
或者你可以随时入伍。
免责声明:我提供的代码是一个指南和未编译的。您需要修改SessionTimer
,以便能够处理多次登记的人员,甚至更多。这取决于你完成它。