Be careful if you use multithreading or multitasking! If so, here you are code and a means to extend the ExpAfter method (.net 4.0):
private static object syncObj = new object(); public static void CancelAfter(this CancellationTokenSource source, int timeoutMilliseconds, Action code = null) { if (timeoutMilliseconds == 0) return; // No timeout if (source == null) { throw new NullReferenceException(); } if (timeoutMilliseconds < -1) { throw new ArgumentOutOfRangeException("timeout"); } Timer timer = new Timer(delegate(object self) { lock (syncObj) { try { if (null != code) code.Invoke(); source.Cancel(); ((IDisposable)self).Dispose(); } catch (ObjectDisposedException) { } } }); timer.Change(timeoutMilliseconds, -1); } }
Regards, Juanlu, ElGuerre
source share