Ejemplo n.º 1
0
        /// <summary>
        /// Call handler periodically
        /// </summary>
        /// <param name="handler">The callback function.</param>
        /// <param name="timeout">Time interval in milliseconds between handler calls.</param>
        /// <param name="data">The arguments to be passed to the handler.</param>
        /// <returns></returns>
        public int SetInterval(Action <object[]> handler, int timeout, object[] data)
        {
            ManualResetEvent stoppedSignal = new ManualResetEvent(false);
            bool             stopped       = false;
            var        container           = new Timer[1];
            Disposable disp;

            lock (_activeTimers)
            {
                disp = new Disposable(() =>
                {
                    stopped = true;
                    if (!stoppedSignal.WaitOne(10000))
                    {
                        lock (container)
                        {
                            if (container[0] != null)
                            {
                                container[0].Dispose();
                                container[0] = null;
                            }
                        }
                    }
                });
                _activeTimers.Add(disp);
            }

            var timer = new Timer(state =>
            {
                lock (_getSyncObj())
                {
                    try
                    {
                        if (!stopped)
                        {
                            handler(data);
                        }
                        else
                        {
                            lock (container)
                            {
                                if (container[0] != null)
                                {
                                    container[0].Dispose();
                                    container[0] = null;
                                    stoppedSignal.Set();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (OnException != null)
                        {
                            OnException(e);
                        }
                    }
                }
            }, null, 0, timeout);

            container[0] = timer;

            return(disp.GetHashCode());
        }