Javascript SetTimeout, SetInterval and ClearInterval equivalent in C #

In many cases, I need to use these functions in C #. My projects should be .NET 4.0, and the following code is the result that I was able to write after reading questions and answers about these functions. I used them for a while and did not have any problems. However, playing with threads is dangerous, so I doubt that I am doing it wrong or not.

My question is that these functions are safe to use; or is there a better way to do this for .NET 4.0?

private static volatile List<System.Threading.Timer> _timers = new List<System.Threading.Timer>(); private static object lockobj = new object(); public static void SetTimeout(Action action, int delayInMilliseconds) { System.Threading.Timer timer = null; var cb = new System.Threading.TimerCallback((state) => { lock (lockobj) _timers.Remove(timer); timer.Dispose(); action(); }); lock (lockobj) _timers.Add(timer = new System.Threading.Timer(cb, null, delayInMilliseconds, System.Threading.Timeout.Infinite)); } private static volatile Dictionary<Guid, System.Threading.Timer> _timers2 = new Dictionary<Guid, System.Threading.Timer>(); private static object lockobj2 = new object(); public static Guid SetInterval(Action action, int delayInMilliseconds) { System.Threading.Timer timer = null; var cb = new System.Threading.TimerCallback((state) => action()); lock (lockobj2) { Guid guid = Guid.NewGuid(); _timers2.Add(guid, timer = new System.Threading.Timer(cb, null, delayInMilliseconds, delayInMilliseconds)); return guid; } } public static bool ClearInterval(Guid guid) { lock (lockobj2) { if (!_timers2.ContainsKey(guid)) return false; else { var t = _timers2[guid]; _timers2.Remove(guid); t.Dispose(); return true; } } } 
+2
javascript c #
source share
1 answer

The only drawback that I have been able to find so far is that if there is an action being taken, the application cannot exit. At the end of the application, this function should be called:

  public static void Free() { lock (lockobj) { foreach (var t in _timers) t.Dispose(); _timers.Clear(); } lock (lockobj2) { foreach (var key in _timers2.Keys.ToList()) ClearInterval(key); } } 
0
source share

All Articles