之前都是通过DateTime.UtcNow来获取时间间隔,后来发现 Environment.TickCount 相比DateTime.UtvNow快了20多倍,就用Environment.TickCount实现了个限制器
测试代码
static TimeLimiter timeLimiter = new TimeLimiter(); static void Test() { while (true) { Dosomething(); Thread.Sleep(200); } } static void Dosomething() { if (timeLimiter.Limiting("abc_123_@#$", 1000)) { return; } Console.WriteLine(DateTime.Now + " 执行具体业务"); }View Code
TimeLimiter
/// <summary> /// 时间限制器,限制一定时间内只能执行一次操作 /// </summary> public class TimeLimiter { readonly Dictionary<string, uint> dict = new Dictionary<string, uint>(); uint prev; readonly object _lock = new object(); /// <summary> /// 判断flag操作是否在milliseconds间隔限制内 /// </summary> public bool Limiting(string flag, uint milliseconds) { uint tc = (uint)Environment.TickCount; //4294967295/1000/86400=49.71天后就会从0开始 if (prev > tc) { //如果前一个值大于当前值,就说明从0开始了 lock (_lock) { if (prev > tc) { dict.Clear(); //清空所有记录,避免永远处于限制状态 } } } prev = tc; if (!dict.ContainsKey(flag)) { dict.Add(flag, tc + milliseconds); return false; } if (tc < dict[flag]) { //当前时间未超过上次指定的限制时间就认为是限制中 return true; } dict[flag] = tc + milliseconds; return false; } }View Code
标签:C#,TickCount,Environment,flag,dict,tc,TimeLimiter From: https://www.cnblogs.com/luludongxu/p/17621079.html