using JNPF.DependencyInjection; namespace Tnb.ProductionMgr.Helpers { public class TimerPoolHelper : ISingleton { private static TimerPoolHelper instance = null; public static TimerPoolHelper GetInstance() { if (instance == null) { if (instance == null) { instance = new TimerPoolHelper(); } } return instance; } private readonly Dictionary _timers = new Dictionary(); private readonly object _lockObject = new object(); public TimerPoolHelper() { // 初始化代码,如果有必要的话 } public void StartTimer(TimerCallback timerCallback,object data,TimeSpan dueTime, TimeSpan period,bool autoClode = true) { Timer timer; lock (_lockObject) { string timestamp = DateTime.Now.Ticks.ToString(); Dictionary dic = new Dictionary(); dic.Add("key",timestamp); dic.Add("value",data); if (autoClode) { timerCallback += DisposeTimer; } timer = new Timer(timerCallback, dic, dueTime, period); _timers.Add(timestamp,timer); } } public void DisposeTimer(object args) { Dictionary dic = (Dictionary)args; string key = dic["key"]!=null ? dic["key"].ToString() : ""; if (_timers.ContainsKey(key)) { _timers[dic["key"].ToString()].Dispose(); _timers[dic["key"].ToString()] = null; _timers.Remove(dic["key"].ToString()); } } } }