Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Exemplo n.º 1
0
        public void DoSend(string locationSemantic, IEnvelope message, int timeout)
        {
            var timer = new Timer(timeout * 1000);
            m_location = locationSemantic;

            try
            {
                _is_completed = false;

                timer.Elapsed += Timer_Elasped;
                timer.Start();

                this.DoSend(locationSemantic, message);
                _is_completed = true;

                timer.Stop();
            }
            catch (Exception exception)
            {
                timer.Stop();
                throw;
            }
            finally
            {
                if (timer.Enabled)
                    timer.Stop();

                timer.Elapsed -= Timer_Elasped;
                timer.Dispose();
            }

        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScriptAssemblyCache"/> class.
        /// </summary>
        ScriptAssemblyCache()
        {
            // Get the cache directory
            _cacheDir = ContentPaths.Build.Data.Join("ScriptCache");
            if (!_cacheDir.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
                !_cacheDir.EndsWith(Path.AltDirectorySeparatorChar.ToString()))
                _cacheDir += Path.DirectorySeparatorChar;

            // Ensure the directory exists
            if (!Directory.Exists(_cacheDir))
                Directory.CreateDirectory(_cacheDir);

            // Load the cache
            Load();

            // Create the saving timer
            _saveAndCleanTimer = new Timer { Interval = _autoSaveRate, AutoReset = true };
            _saveAndCleanTimer.Elapsed += _saveTimer_Elapsed;
            _saveAndCleanTimer.Start();

            // Spawn a new background timer to clean up the junk files a few seconds from now
            var cleanTimer = new Timer { Interval = 5 * 1000, AutoReset = false };
            cleanTimer.Elapsed += delegate
            {
                cleanTimer.Dispose();
                RemoveUnusedCacheFiles();
            };
            cleanTimer.Start();
        }
Exemplo n.º 3
0
        public void Dispose()
        {
            _headersRequests?.Dispose();
            _bodiesRequests?.Dispose();

            _txFloodCheckTimer.Elapsed -= CheckTxFlooding;
            _txFloodCheckTimer?.Dispose();
        }
 public void Dispose()
 {
     _base.Dispose();
     Timer?.Dispose();
     Timer = null;
     Stream?.Dispose();
     Stream = null;
     Reader?.Dispose();
     Reader = null;
 }
Exemplo n.º 5
0
        public void Dispose()
        {
            MoveTimer.Elapsed -= MoveTimer_Elapsed;
            MoveTimer.Enabled  = false;
            MoveTimer?.Dispose();

            AppleTimer.Elapsed -= AppleTimer_Elapsed;
            AppleTimer.Enabled  = false;
            AppleTimer?.Dispose();
        }
Exemplo n.º 6
0
 static void TimersTimer()
 {
     System.Timers.Timer t1 = new System.Timers.Timer(1000);
     t1.AutoReset = true;
     t1.Elapsed += TimeAction;
     t1.Start();
     Thread.Sleep(10000);
     t1.Stop();
     t1.Dispose();
 }
Exemplo n.º 7
0
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            ++x;
            // Invalidate chart for refresh
            Plot.Model.InvalidatePlot(true);
            if (this.counter == 10)
            {
                s1.Points.Add(new DataPoint(x, y + 1));
                reverse = true;
            }
            if (this.counter == 0)
            {
                reverse = false;
            }

            if (reverse)
            {
                counter--;
            }
            else
            {
                counter++;
            }

            if (reverse)
            {
                y--;
            }
            else
            {
                y++;
            }
            // Add lines
            if (reverse)
            {
                s1.Points.Add(new DataPoint(x, y + 1));
                s1.Points.Add(new DataPoint(x, y));
            }
            else
            {
                s1.Points.Add(new DataPoint(x, y));
                s1.Points.Add(new DataPoint(x, y + 1));
            }
            // Change axis
            if (x > axis1.Maximum - 2)
            {
                axis1.Maximum += 10;
            }

            if (axis1.Maximum == 30)
            {
                aTimer.Stop();
                aTimer?.Dispose();
            }
        }
Exemplo n.º 8
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             _timeoutBetweenClipDownloadingTimer?.Dispose();
         }
     }
     _disposed = true;
 }
Exemplo n.º 9
0
 public void OnCreated(ILoading loading)
 {
     DestroyOld ("DistrictRCIDemand");
     var timer = new Timer (10000); //delays GUI hook so other mods such as Building Themes can do its thing
     timer.Elapsed += (object sender, ElapsedEventArgs e) => {
         HookGUI();
         timer.Enabled = false;
         timer.Dispose();
     };
     timer.Enabled = true;
 }
Exemplo n.º 10
0
        public async void ProcessRequest(HttpContext context)
        {
            //validate query parameters
            QueryParams queryParams;
            try
            {
                queryParams = new QueryParams(context.Request);
            }
            catch
            {
                context.Response.StatusCode = 400; //bad request
                return;
            }

            //convert query parameters to entities            
            var ctx = new DiscCtx(ConfigManager.ConnStr);
            var reportParams = queryParams.Materialize(ctx);
            if (reportParams == null)
            {
                context.Response.StatusCode = 400;
                return;
            }

            var screenshotClient = new ReportingPhotonClient();
            var reportingTasks = screenshotClient.StartReportingActivities(reportParams.Topic,
                                                                           reportParams.Discussion,
                                                                           reportParams.Session);
            var complexReportTask = reportingTasks.Item2;

            //compute and set report parameters 
            var report = new Report
                {
                    QueryParams = queryParams,
                    ReportParams = reportParams,
                    Participants = Helpers.ParticipantsTuples(reportParams.Topic, reportParams.Session),
                    ComplexReport  = await complexReportTask,
                    ReportUrl = context.Request.Url.ToString(),
                    BaseUrl = Helpers.BaseUrl(context.Request)
                };

            var screenshotTask = reportingTasks.Item1;
            report.ReceiveScreenshots(await screenshotTask, context);

            var cleanupTimer = new Timer(10*60*1000); //10 minutes
            cleanupTimer.Elapsed += (sender, args) =>
                {
                    cleanupTimer.Dispose();
                    report.Dispose();
                    screenshotClient.Dispose();
                };   
           cleanupTimer.Start();

           context.Response.Write(report.TransformText());
        }
Exemplo n.º 11
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             _timer?.Dispose();
         }
     }
     _disposed = true;
 }
Exemplo n.º 12
0
 public void Timer_Dispose_noTicksAnymore()
 {
     global::System.Timers.Timer t = new Timer(100);
     var tc = 0;
     t.Elapsed += (s, e) => tc++;
     t.Start();
     Thread.Sleep(200);
     t.Dispose();
     Thread.Sleep(500);
     Assert.Less(tc,3);
     Assert.GreaterOrEqual(tc, 1);
 }
Exemplo n.º 13
0
        public void Dispose()
        {
            _reconnectTimer?.Dispose();

            if (_client != null)
            {
                _client.Dispose();
                _client = null;
            }

            _frontContractRequests?.Dispose();
        }
Exemplo n.º 14
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _timer?.Dispose();
                }

                disposedValue = true;
            }
        }
Exemplo n.º 15
0
        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _sponge?.DestroyHandle();
                _sponge = null;
                _taskManagerTimer?.Dispose();
                _taskManagerTimer = null;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 16
0
        public WindowsService()
        {
            smsTimer = new Timer();
            diffTimer = new Timer();
            fullTimer = new Timer();
            registery = new RegistrySettingManager();
            sqlserverManagment = new SqlServerManagement(registery.SqlServer, registery.SqlServerInstance);

            file.AutoFlush = true;
            file.WriteLine("service newed");
            // timer for sms
            smsTimer.Interval = 12 * 60 * 60 * 1000;//har 12 saat
            smsTimer.AutoReset = true;
            smsTimer.Enabled = true;
            smsTimer.Elapsed += (x, y) => onSmsTimerElapsed();
            // timer for diff backup
            diffTimer.Interval = 60 * 1000;//har 1 daghighe
            diffTimer.AutoReset = true;
            diffTimer.Enabled = true;
            diffTimer.Elapsed += (x, y) => {
                if (registery.AutomaticBackup
                    && registery.LastDiffBackUpTime.HasValue
                    && (DateTime.Now - registery.LastDiffBackUpTime.Value).TotalHours >= registery.DiffBackUpPeriod
                    )
                onDiffTimerElapsed();
            };
            // timer for full backup
            fullTimer.Interval = 60*60*1000;//har 1 saat
            fullTimer.AutoReset = true;
            fullTimer.Enabled = true;
            fullTimer.Elapsed += (x, y) =>
            {
                if (registery.AutomaticBackup
                    && registery.LastFullBackUpTime.HasValue
                    && (DateTime.Now - registery.LastFullBackUpTime.Value).TotalDays == registery.FullBackUpPeriod
                    && DateTime.Parse(registery.FullBackUpTime).TimeOfDay >= DateTime.Now.TimeOfDay)
                    onFullTimerElapsed();
            };

            this.Disposed += (x, y) => { smsTimer.Dispose(); fullTimer.Dispose(); diffTimer.Dispose(); file.Close(); };

            //service setting
            this.ServiceName = "ShayanDentalBackUp";
            this.EventLog.Log = "Application";
            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;

            file.WriteLine("service new" + DateTime.Now);
        }
Exemplo n.º 17
0
        public PortSelector(bool isNetworkAvailable) {
            InitializeComponent();
            DeviceRadioButton.Checked += (s, e) => ConnectCommand.RaiseCanExecuteChanged();
            NetworkRadioButton.Checked += (s, e) => ConnectCommand.RaiseCanExecuteChanged();

            if (!isNetworkAvailable) NetworkRadioButton.Visibility = NetworkControl.Visibility = Visibility.Collapsed;

            timer = new Timer {AutoReset = true, Interval = 1000};
            timer.Elapsed += timer_Elapsed;
            timer.Start();

            Closed += (s, e) => timer.Dispose();
        }
Exemplo n.º 18
0
 public static void Delay(this Action action, int delayInMilliseconds)
 {
     var timer = new Timer
     {
         Interval = delayInMilliseconds,
         AutoReset = false
     };
     timer.Elapsed += delegate
     {
         timer.Dispose();
         action();
     };
     timer.Start();
 }
Exemplo n.º 19
0
 public int CreatePlayerAndGetId(string fileName, uint options)
 {
     if (options == 1)
     {
         var timer = new Timer(10);
         timer.Elapsed += (sender, args) =>
         {
             _eventsProvider.Publish(new PlayerCompleted() {Id = 0});
             timer.Dispose();
         };
         timer.Enabled = true;
     }
     return 0;
 }
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    lock (timerLocker)
                    {
                        Timer?.Dispose();
                    }
                }
                disposedValue = true;
            }
        }
        public void Dispose()
        {
            lock (_lockObject)
            {
                _clientSocket?.Close();
                _clientSocket?.Dispose();

                _udpClient?.Close();
                _udpClient?.Dispose();

                _timeoutTimer?.Close();
                _timeoutTimer?.Dispose();
            }
        }
Exemplo n.º 22
0
        public ChannelListUpdaterService(IChatState chatState)
        {
            connection = chatState.Connection;
            cm = chatState.ChatModel;

            chatState.EventAggregator.GetEvent<ConnectionClosedEvent>().Subscribe(OnWipeState);

            var timer = new Timer(60*1000*1);
            timer.Elapsed += (s, e) =>
            {
                UpdateChannels();
                timer.Dispose();
            };
            timer.Start();
        }
Exemplo n.º 23
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _PingTimer.Dispose();
                    _PongTimer?.Dispose();
                }

                _Socket.Dispose();

                disposedValue = true;
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            RenderToLedSign(DateTime.Now.ToString("HH:mm"));

            m_clockTimer = new Timer();
            m_clockTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
            m_clockTimer.Elapsed += (s,e) => RenderToLedSign(DateTime.Now.ToString("HH:mm"));
            m_clockTimer.Start();

            Console.WriteLine("Press <Enter> to exit.");
            Console.ReadLine();

            m_clockTimer.Stop();
            m_clockTimer.Dispose();
        }
Exemplo n.º 25
0
        private void FinishTask(ITask task)
        {
            var TaskType = task.GetType();
            var NextTime = task.NextExecutionTime();
            _TaskFactory.DestroyTask(task);

            var Timer = new Timer();
            Timer.Elapsed += (o, e) =>
                {
                    Timer.Dispose();
                    CreateTask(TaskType);
                };
            Timer.Interval = NextTime.TotalMilliseconds;
            Timer.Start();
        }
Exemplo n.º 26
0
        public void OnLevelLoaded(LoadMode mode)
        {
            if (!(mode == LoadMode.LoadGame || mode == LoadMode.NewGame)) {
                return;
            }
            Debug.Print ("OnLevelLoaded()");
            DestroyOld ("DistrictRCIDemand");
            var timer = new Timer (10000); //delays GUI hook so other mods such as Building Themes can do its thing
            timer.Elapsed += (object sender, ElapsedEventArgs e) => {
                HookGUI();
                timer.Enabled = false;
                timer.Dispose();
            };

            timer.Enabled = true;
        }
        protected virtual void Dispose(bool disposing)
        {
            mLogger.LogDebug("Closing timer");

            if (mDisposed)
            {
                return;
            }

            if (disposing)
            {
                mTriangleNotifierTimer?.Dispose();
            }

            mDisposed = true;
        }
Exemplo n.º 28
0
 public static void TimedUnlock() 
 {
     if(Unlock) 
     {
         // Hook up the Elapsed event for the timer. 
         var timer = new Timer(300);
     
         timer.Elapsed += delegate(System.Object source, ElapsedEventArgs e) 
         {
             timer.Enabled = false;
             timer.Dispose();
             UnlockPolicyToolbarButton();
         };
         timer.Enabled = true;
     }
 }
Exemplo n.º 29
0
        private void Startup_Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            appStartupTimer?.Stop();
            appStartupTimer?.Dispose();

            this.Dispatcher.Invoke((Action) delegate()
            {
                PaymentActionEventArgs ePayment = new PaymentActionEventArgs()
                {
                    SessionId  = "DEADBEEF-BADDCACA",
                    Message    = "Payment",
                    ButtonText = "Cancel Payment",
                    Timeout    = 5000
                };
                DalMonitorManager_OnTransactionRequested(sender, ePayment);
            });
        }
Exemplo n.º 30
0
        public void Destory()
        {
            _timer?.Stop();
            _timer?.Dispose();

            _isClosed = true;
            if (_ws != null)
            {
                if (_ws.State != WebSocketState.Closed && _ws.State != WebSocketState.None)
                {
                    _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }

                _ws.Dispose();
                _binaryWriter.Dispose();
            }
        }
Exemplo n.º 31
0
        static void Main(string[] arg)
        {
            Timer tmr = new Timer();
            tmr.Interval = 1000;

            tmr.Elapsed += tmr_Elapsed;
            tmr.Start();

            Console.ReadLine();
            tmr.Stop();         // Stop the timer

            Console.ReadLine();
            tmr.Start();        // Restart the timer

            Console.ReadLine();
            tmr.Dispose();  // 停止计时器并释放相关资源
        }
Exemplo n.º 32
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource.Dispose();
                _helpPostTimer?.Stop();
                _helpPostTimer?.Dispose();
            }

            disposed = true;
        }
        public NotificationEventArgs(string tag, string eventName, string timestamp = "000000000000000", int delayTime = 10000)
        {
            Tag = tag;
            EventName = eventName;
            Timestamp = timestamp;

            // our timer
            var timer = new Timer {Interval = delayTime};
            // function that cálled after time elapsed
                timer.Elapsed += (sender, args) =>
                {
                    StopMeEvent?.Invoke(this, Empty);
                    timer.Stop();
                    timer.Dispose();
                };
                timer.Start();
        }
Exemplo n.º 34
0
        public void Run()
        {
            string filePath;

            do
            {
                 Console.WriteLine("Please write the path to the file you wish to import the data");
                filePath = Console.ReadLine();
            } while (string.IsNullOrEmpty(filePath));

            Console.WriteLine("Initiate Importing Process...");
            Timer aTimer = new Timer(1000);
            aTimer.Elapsed += OnTimedEvent;
            aTimer.Start();

            List<Address> addressList = new List<Address>();
            Dictionary<string, string> postalCodes = new Dictionary<string, string>();
            IncludeHeaderInCsvFile(filePath);
            var textStream = File.OpenText(filePath);
            var csv = new CsvReader(textStream);
            csv.Configuration.AutoMap<FileLineDetails>();

            while (csv.Read())
            {
                var addressLine1 = csv.GetField<string>("AddressLine1");
                var addressLine2 = csv.GetField<string>("AddressLine2");
                var city = csv.GetField<string>("City");
                var postalCode = csv.GetField<string>("PostalCode");
                if (!postalCodes.ContainsKey(postalCode.ToLower().Replace(" ", "")))
                {
                    var address = _addressBuilder.BuildAddress(addressLine1, addressLine2, city, postalCode);
                    if (address != null)
                    {
                        postalCodes.Add(address.PostalCode.ToLower().Replace(" ", ""), address.PostalCode.ToLower().Replace(" ", ""));
                        addressList.Add(address);
                    }
                }
            }

            _addressService.Add(addressList);
            aTimer.Stop();
            aTimer.Dispose();
            Console.WriteLine("Press Any Key to Exit...");
            Console.Read();
        }
Exemplo n.º 35
0
        private Timer StartNewReminder(Reminder r)
        {
            var now = DateTime.Now;
            var twoMins = new TimeSpan(0, 2, 0);
            TimeSpan time = (r.When - now) < twoMins
                            ? twoMins       //if the time is less than 2 minutes,
                            : r.When - now; //it will send the message 2 minutes after start
                                            //To account for high bot startup times
            if (time.TotalMilliseconds > int.MaxValue)
                return null;
            var t = new Timer(time.TotalMilliseconds);
            t.Elapsed += async (s, e) =>
            {
                try
                {
                    Channel ch;
                    if (r.IsPrivate)
                    {
                        ch = NadekoBot.Client.PrivateChannels.FirstOrDefault(c => (long)c.Id == r.ChannelId);
                        if (ch == null)
                            ch = await NadekoBot.Client.CreatePrivateChannel((ulong)r.ChannelId);
                    }
                    else
                        ch = NadekoBot.Client.GetServer((ulong)r.ServerId)?.GetChannel((ulong)r.ChannelId);

                    if (ch == null)
                        return;

                    await ch.SendMessage($"❗⏰**I've been told to remind you to '{r.Message}' now by <@{r.UserId}>.**⏰❗");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Timer error! {ex}");
                }
                finally
                {
                    DbHandler.Instance.Delete<Reminder>(r.Id.Value);
                    t.Stop();
                    t.Dispose();
                }
            };
            t.Start();
            return t;
        }
Exemplo n.º 36
0
        public void Track() {
            _DelayedTrack = new Timer(30*1000 /*30 sec delay*/) { AutoReset = true, Enabled = true};
            _DelayedTrack.Elapsed += (o, e) => {
                                        try {
                                            if (_Tries > 10) {
                                                _DelayedTrack.Stop();
                                            }

                                            TrackUsageInternal();
                                            _DelayedTrack.Stop();
                                            _DelayedTrack.Dispose();
                                        }
                                        catch (Exception exc) {
                                            _Logger.WarnException("Failed to track usage", exc);
                                            _Tries++;
                                        }
                                     };

        }
Exemplo n.º 37
0
        public void Dispose()
        {
            syncRoot?.Dispose();
            syncRoot = null;

            savingSemaphore?.Dispose();
            savingSemaphore = null;

            saveTimer?.Stop();
            saveTimer?.Dispose();
            saveTimer = null;

            updateTimer?.Stop();
            updateTimer?.Dispose();
            updateTimer = null;

            PriceHistoryManager?.Dispose();
            PriceHistoryManager  = null;
            TradesHistoryManager = null;
        }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            timer = new Timer(new TimeSpan(0, 0, 30).TotalMilliseconds);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            Console.WriteLine("Host starting...");
            container = new Container();
            timer.Start();

            Console.WriteLine("Host started. Press any key to exit...");
            Console.ReadKey();

            if (timer != null)
            {
                timer.Stop();
                timer.Dispose();
            }

            container.StopAllServices();
        }
Exemplo n.º 39
0
 protected override void Process(IMessage input, Action<IMessage> continueWith, Action<FlowRuntimeException> unhandledException)
 {
     message = input;
     if (timer == null) {
         timer = new Timer {
             Interval = periodInMilliseconds
         };
         timer.Elapsed +=
             delegate {
                 timer.Dispose();
                 timer = null;
                 continueWith(message);
             };
         timer.Start();
     }
     else {
         timer.Stop();
         timer.Start();
     }
 }
Exemplo n.º 40
0
        /////////////////////////////////////////////////
        /// Handler function for when the Web Api requests
        /// to set the timers on Poomba
        /////////////////////////////////////////////////
        private static void UpdateTime(string message)
        {
            Console.WriteLine("Poomba: Asked to update timers");
            WebApiConnector connector = new WebApiConnector();
            //Get latest PoombaObject from database
            string     json   = connector.GetItem("Poomba/Newest");
            PoombaItem poomba = JsonConvert.DeserializeObject <PoombaItem>(json);

            //Find time for next sleep time
            TimeSpan timeToTurnOff = poomba.SleepTime - DateTime.Now;
            TimeSpan timeToTurnOn  = poomba.WakeUpTime - DateTime.Now;

            // Increment TimeSpan by one day until the day matches with current day
            while (timeToTurnOff < TimeSpan.Zero)
            {
                timeToTurnOff = timeToTurnOff + TimeSpan.FromDays(1);
            }

            while (timeToTurnOn < TimeSpan.Zero)
            {
                timeToTurnOn = timeToTurnOn + TimeSpan.FromDays(1);
            }

            Console.WriteLine("Poomba: Timer for wakeup is now in: {0} hours", timeToTurnOn.TotalHours);
            Console.WriteLine("Poomba: Timer for sleep is now in: {0} hours", timeToTurnOff.TotalHours);

            //Set up timer for automatic sleep
            _sleepTimer?.Dispose();
            _wakeUpTimer?.Dispose();

            _sleepTimer           = new System.Timers.Timer(timeToTurnOff.TotalMilliseconds);
            _sleepTimer.Elapsed  += Sleep;
            _sleepTimer.AutoReset = false;
            _sleepTimer.Start();


            _wakeUpTimer           = new System.Timers.Timer(timeToTurnOn.TotalMilliseconds);
            _wakeUpTimer.Elapsed  += WakeUp;
            _wakeUpTimer.AutoReset = false;
            _wakeUpTimer.Start();
        }
Exemplo n.º 41
0
 private void InitilizeProgressTimer()
 {
     stopWatch.Start();
     bool throwing = false;
     try
     {
         progressTimer = new Timer
         {
             AutoReset = false,
             Interval = progressInterval.TotalMilliseconds
         };
         progressTimerOnElapsed = (sender, args) =>
         {
             ProgressRecord pr;
             if (progressStatus.TryGetProgressRecord(out pr))
             {
                 this.progress(pr);
             }
             progressTimer.Enabled = true;
         };
         progressTimer.Elapsed += progressTimerOnElapsed;
         progressTimer.Enabled = true;
     }
     catch (Exception)
     {
         throwing = true;
         throw;
     }
     finally
     {
         if (throwing && progressTimer != null)
         {
             progressTimer.Elapsed -= progressTimerOnElapsed;
             progressTimer.Enabled = false;
             progressTimer.Dispose();
             progressTimer = null;
         }
     }
 }
Exemplo n.º 42
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="CacheCount" /> class.
        ///     creates a new cached count of something
        /// </summary>
        /// <param name="getNewCount">
        ///     function used to get the new count
        /// </param>
        /// <param name="updateResolution">
        ///     how often, in seconds, it is updated
        /// </param>
        /// <param name="wait">
        ///     The wait.
        /// </param>
        public CacheCount(Func<int> getNewCount, int updateResolution, int wait = 0)
        {
            oldCounts = new List<int>();
            this.getNewCount = getNewCount;
            this.updateResolution = updateResolution;

            updateTick = new Timer(updateResolution*1000);
            updateTick.Elapsed += (s, e) => Update();

            if (wait > 0)
            {
                var waitToStartTick = new Timer(wait);
                waitToStartTick.Elapsed += (s, e) =>
                {
                    updateTick.Start();
                    waitToStartTick.Dispose();
                };
                waitToStartTick.Start();
            }
            else
                updateTick.Start();
        }
Exemplo n.º 43
0
 public void ReviewTimer()
 {
     this.canusereview = false;
     System.Timers.Timer Clock = new System.Timers.Timer(1000 * Server.reviewcooldown);
     Clock.Elapsed += delegate { this.canusereview = true; Clock.Dispose(); };
     Clock.Start();
 }
Exemplo n.º 44
0
        // Detaches from events, stops, and disposes of the dump timer.
        // Also resets the statistics that were gathered since the creation
        // of the stat timer. Timers created through the CreateStatTimer
        // method should be released through this method.
        private void ReleaseStatTimer(Timer statTimer)
        {
            if (statTimer != null)
            {
                statTimer.Elapsed -= StatTimer_Elapsed;
                statTimer.Stop();
                statTimer.Dispose();
            }

            // Reset statistics
            m_measurementCount = 0L;
            m_lastMeasurementCount = 0L;
            m_lastTotalBytesReceived = 0L;
            m_lastStatCalcTime = 0L;

            if (StatsUpdated != null)
                StatsUpdated(this, new EventArgs<int, int, float, double>(0, 0, 0.0F, double.NaN));
        }
Exemplo n.º 45
0
        public void EndVote()
        {
            if (!voteActive) return;

            voteActive = false;
            Server.s.Log("[Lava Survival] Vote ended.");
            KeyValuePair<string, int> most = new KeyValuePair<string, int>(String.Empty, -1);
            foreach (KeyValuePair<string, int> kvp in votes)
            {
                if (kvp.Value > most.Value) most = kvp;
                map.ChatLevelOps("&5" + kvp.Key.Capitalize() + "&f: &a" + kvp.Value);
            }
            votes.Clear();
            voted.Clear();

            if (OnVoteEnd != null)
                OnVoteEnd(most.Key);
            map.ChatLevel("The vote has ended! &5" + most.Key.Capitalize() + Server.DefaultColor + " won with &a" + most.Value + Server.DefaultColor + " vote" + (most.Value == 1 ? "" : "s") + ".");
            map.ChatLevel("You will be transferred in 5 seconds...");
            transferTimer = new Timer(5000);
            transferTimer.AutoReset = false;
            transferTimer.Elapsed += delegate
            {
                try
                {
                    LoadMap(most.Key);
                    transferTimer.Dispose();
                }
                catch (Exception e) { Server.ErrorLog(e); }
            };
            transferTimer.Start();
        }
Exemplo n.º 46
0
        public void StartVote()
        {
            if (maps.Count < 3) return;

            // Make sure these are cleared or bad stuff happens!
            votes.Clear();
            voted.Clear();

            byte i = 0;
            string opt, str = "";
            while (i < Math.Min(voteCount, maps.Count - 1))
            {
                opt = maps[rand.Next(maps.Count)];
                if (!votes.ContainsKey(opt) && opt != map.name)
                {
                    votes.Add(opt, 0);
                    str += Server.DefaultColor + ", &5" + opt.Capitalize();
                    i++;
                }
            }

            if (OnVoteStart != null)
                OnVoteStart(votes.Keys.ToList().ToArray());
            map.ChatLevel("Vote for the next map! The vote ends in " + voteTime + " minute" + (voteTime == 1 ? "" : "s") +".");
            map.ChatLevel("Choices: " + str.Remove(0, 4));

            voteTimer = new Timer(TimeSpan.FromMinutes(voteTime).TotalMilliseconds);
            voteTimer.AutoReset = false;
            voteTimer.Elapsed += delegate
            {
                try
                {
                    EndVote();
                    voteTimer.Dispose();
                }
                catch (Exception e) { Server.ErrorLog(e); }
            };
            voteTimer.Start();
            voteActive = true;
        }
Exemplo n.º 47
0
        void Init(Action toRun)
        {
            var nextBuild = GetNextBuild();
            var nextInterval = nextBuild - TimeHelper.Now;

            _timer = new Timer(nextInterval.TotalMilliseconds);
            _timer.Elapsed += (obj, args) =>
            {
                try
                {
                    _lastBuild = TimeHelper.Now;
                    toRun();
                }
                finally
                {
                    _timer.Stop();
                    _timer.Dispose();
                    Init(toRun);
                }
            };

            _timer.Start();
        }
        public void TestUnthrottledFloodPublishing()
        {
            Conn.ConnectionShutdown += (_, args) =>
            {
                if (args.Initiator != ShutdownInitiator.Application)
                {
                    Assert.Fail("Unexpected connection shutdown!");
                }
            };

            bool elapsed = false;
            var t = new System.Timers.Timer(1000 * 185);
            t.Elapsed += (_sender, _args) => { elapsed = true; };
            t.AutoReset = false;
            t.Start();

            while (!elapsed)
            {
                Model.BasicPublish("", "", null, new byte[2048]);
            }
            Assert.IsTrue(Conn.IsOpen);
            t.Dispose();
        }