protected static void PrepareDCObject(DelayedCall dc, int milliseconds, bool async) { if (milliseconds < 0) { throw new ArgumentOutOfRangeException("milliseconds", "The new timeout must be 0 or greater."); } // Get the current synchronization context if required, with dummy fallback dc.context = null; if (!async) { dc.context = SynchronizationContext.Current; if (dc.context == null) throw new InvalidOperationException("Cannot delay calls synchronously on a non-UI thread. Use the *Async methods instead."); } if (dc.context == null) dc.context = new SynchronizationContext(); // Run asynchronously silently dc.timer = new System.Timers.Timer(); if (milliseconds > 0) dc.timer.Interval = milliseconds; dc.timer.AutoReset = false; dc.timer.Elapsed += dc.Timer_Elapsed; Register(dc); }
protected static void Unregister(DelayedCall dc) { lock (dcList) { // Free a reference on this object to allow the Garbage Collector to dispose it // if no other reference is kept to it dcList.Remove(dc); } }
/// <summary> /// Creates a new asynchronous <c>DelayedCall</c> instance. The callback function will be invoked on a <c>ThreadPool</c> thread. /// </summary> /// <param name="cb">Callback function</param> /// <param name="milliseconds">Time to callback invocation</param> /// <returns>Newly created <c>DelayedCall</c> instance that can be used for later controlling of the invocation process</returns> public static DelayedCall CreateAsync(Callback cb, int milliseconds) { DelayedCall dc = new DelayedCall(); PrepareDCObject(dc, milliseconds, true); dc.callback = cb; return dc; }
protected static void Register(DelayedCall dc) { lock (dcList) { // Keep a reference on this object to prevent it from being caught by the Garbage Collector if (!dcList.Contains(dc)) dcList.Add(dc); } }