System.Threading.Timer.Change(int, int)

Here are the examples of the csharp api System.Threading.Timer.Change(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

547 Examples 7

19 View Source File : RulePoller.cs
License : Apache License 2.0
Project Creator : aws

internal void WakeUp()
        {
            _timer.Dispose();

            // Perform out of band polling
            _timer = new Timer(Start);
            _timer.Change(0, 0);
        }

19 View Source File : TaskbarIcon.cs
License : MIT License
Project Creator : ay2015

public void ShowCustomBalloon(UIElement balloon, PopupAnimation animation, int? timeout)
        {
            Dispatcher dispatcher = this.GetDispatcher();
            if (!dispatcher.CheckAccess())
            {
                var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
                dispatcher.Invoke(DispatcherPriority.Normal, action);
                return;
            }

            if (balloon == null) throw new ArgumentNullException("balloon");
            if (timeout.HasValue && timeout < 500)
            {
                string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
                msg = String.Format(msg, timeout);
                throw new ArgumentOutOfRangeException("timeout", msg);
            }

            EnsureNotDisposed();

            //make sure we don't have an open balloon
            lock (this)
            {
                CloseBalloon();
            }

            //create an invisible popup that hosts the UIElement
            Popup popup = new Popup();
            popup.AllowsTransparency = true;

            //provide the popup with the taskbar icon's data context
            UpdateDataContext(popup, null, DataContext);

            //don't animate by default - devs can use attached
            //events or override
            popup.PopupAnimation = animation;

            //in case the balloon is cleaned up through routed events, the
            //control didn't remove the balloon from its parent popup when
            //if was closed the last time - just make sure it doesn't have
            //a parent that is a popup
            var parent = LogicalTreeHelper.GetParent(balloon) as Popup;
            if (parent != null) parent.Child = null;

            if (parent != null)
            {
                string msg =
                    "Cannot display control [{0}] in a new balloon popup - that control already has a parent. You may consider creating new balloons every time you want to show one.";
                msg = String.Format(msg, balloon);
                throw new InvalidOperationException(msg);
            }

            popup.Child = balloon;

            //don't set the PlacementTarget as it causes the popup to become hidden if the
            //TaskbarIcon's parent is hidden, too...
            //popup.PlacementTarget = this;

            popup.Placement = PlacementMode.AbsolutePoint;
            popup.StaysOpen = true;

            
            Point position = this.CustomPopupPosition != null ? this.CustomPopupPosition() : this.GetPopupTrayPosition();
            popup.HorizontalOffset = position.X - 1;
            popup.VerticalOffset = position.Y - 1;

            //store reference
            lock (this)
            {
                SetCustomBalloon(popup);
            }

            //replacedign this instance as an attached property
            SetParentTaskbarIcon(balloon, this);

            //fire attached event
            RaiseBalloonShowingEvent(balloon, this);

            //display item
            popup.IsOpen = true;

            if (timeout.HasValue)
            {
                //register timer to close the popup
                balloonCloseTimer.Change(timeout.Value, Timeout.Infinite);
            }
        }

19 View Source File : BaseBatchMessageHandler.cs
License : MIT License
Project Creator : AntonyVorontsov

public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Change(Timeout.Infinite, 0);
            _loggingService.LogInformation($"Batch message handler {GetType()} has been stopped.");
            return Task.CompletedTask;
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : awaescher

protected static void RefreshTimerCallback(object state)
		{
			_explorerHandler.Updatereplacedles();
			_explorerUpdateTimer.Change(500, Timeout.Infinite);
		}

19 View Source File : CachePolicyManager.cs
License : MIT License
Project Creator : Avanade

private void TimerElapsed(Object stateInfo)
        {
            lock (_lock)
            {
                _logger?.LogTrace($"{nameof(CachePolicyManager)} flush triggered by timer.");
                _timer?.Change(Timeout.Infinite, Timeout.Infinite);
            }

            Flush();

            lock (_lock)
            {
                if (_timer != null)
                {
                    _logger?.LogTrace($"{nameof(CachePolicyManager)} execution completed. Retry in {_period}.");
                    _timer.Change(_period, _period);
                }
            }
        }

19 View Source File : Scheduler.cs
License : MIT License
Project Creator : anet-team

private static void UpdateTimer()
        {
            if (!_enabled) return;

            var nextToRun = _scheduleList.OrderBy(s => s.NextRunTime).FirstOrDefault();
            if(nextToRun == null)
            {
                _timer.Change(-1, -1);
                return;
            }
            
            _nextToRun = nextToRun;

            var interval = nextToRun.NextRunTime - DateTime.Now;
            if (interval <= TimeSpan.Zero)
            {
                OnTimerCallback();
            }
            else
            {
                _timer.Change(interval, interval);
            }
        }

19 View Source File : TimerPlugin.cs
License : Apache License 2.0
Project Creator : awslabs

private void EnableTimer()
        {
            _timer.Change((int)Interval.TotalMilliseconds, (int)Interval.TotalMilliseconds);
        }

19 View Source File : ShowDesktop.cs
License : MIT License
Project Creator : AlexGyver

private void StopTimer() {
      timer.Change(System.Threading.Timeout.Infinite,
        System.Threading.Timeout.Infinite);
    }

19 View Source File : TaskbarIcon.cs
License : MIT License
Project Creator : ay2015

private void OnMouseEvent(MouseEvent me)
        {
            if (IsDisposed) return;

            switch (me)
            {
                case MouseEvent.MouseMove:
                    RaiseTrayMouseMoveEvent();
                    //immediately return - there's nothing left to evaluate
                    return;
                case MouseEvent.IconRightMouseDown:
                    RaiseTrayRightMouseDownEvent();
                    break;
                case MouseEvent.IconLeftMouseDown:
                    RaiseTrayLeftMouseDownEvent();
                    break;
                case MouseEvent.IconRightMouseUp:
                    RaiseTrayRightMouseUpEvent();
                    break;
                case MouseEvent.IconLeftMouseUp:
                    RaiseTrayLeftMouseUpEvent();
                    break;
                case MouseEvent.IconMiddleMouseDown:
                    RaiseTrayMiddleMouseDownEvent();
                    break;
                case MouseEvent.IconMiddleMouseUp:
                    RaiseTrayMiddleMouseUpEvent();
                    break;
                case MouseEvent.IconDoubleClick:
                    //cancel single click timer
                    singleClickTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    //bubble event
                    RaiseTrayMouseDoubleClickEvent();
                    break;
                case MouseEvent.BalloonToolTipClicked:
                    RaiseTrayBalloonTipClickedEvent();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("me", "Missing handler for mouse event flag: " + me);
            }


            //get mouse coordinates
            Point cursorPosition = new Point();
            if (messageSink.Version == NotifyIconVersion.Vista)
            {
                //physical cursor position is supported for Vista and above
                WinApi.GetPhysicalCursorPos(ref cursorPosition);
            }
            else
            {
                WinApi.GetCursorPos(ref cursorPosition);
            }

            cursorPosition = TrayInfo.GetDeviceCoordinates(cursorPosition);

            bool isLeftClickCommandInvoked = false;

            //show popup, if requested
            if (me.IsMatch(PopupActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show popup once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        ShowTrayPopup(cursorPosition);
                    };
                    singleClickTimer.Change(doubleClickWaitTime, Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show popup immediately
                    ShowTrayPopup(cursorPosition);
                }
            }


            //show context menu, if requested
            if (me.IsMatch(MenuActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show context menu once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        ShowContextMenu(cursorPosition);
                    };
                    singleClickTimer.Change(doubleClickWaitTime, Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show context menu immediately
                    ShowContextMenu(cursorPosition);
                }
            }

            //make sure the left click command is invoked on mouse clicks
            if (me == MouseEvent.IconLeftMouseUp && !isLeftClickCommandInvoked)
            {
                //show context menu once we are sure it's not a double click
                singleClickTimerAction =
                    () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                    };
                singleClickTimer.Change(doubleClickWaitTime, Timeout.Infinite);
            }
        }

19 View Source File : Worker.cs
License : MIT License
Project Creator : alexvolchetsky

public override Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Change(Timeout.Infinite, 0);
            return base.StopAsync(cancellationToken);
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : awaescher

protected override void OnExit(ExitEventArgs e)
		{
			_ipcServer?.Stop();
			_ipcServer?.Dispose();

			_hotkey.Unregister();

			_explorerUpdateTimer.Change(Timeout.Infinite, Timeout.Infinite);

			var explorerHandler = TinyIoCContainer.Current.Resolve<WindowsExplorerHandler>();
			explorerHandler.Cleanreplacedles();

			_notifyIcon.Dispose();

			base.OnExit(e);
		}

19 View Source File : MainForm.cs
License : MIT License
Project Creator : awaescher

private async Task CheckForUpdatesAsync()
		{
			_updateTimer.Change(Timeout.Infinite, Timeout.Infinite);

			var request = new UpdateRequest()
				.WithNameAndVersionFromEntryreplacedembly()
				.AsAnonymousClient()
				.OnChannel("stable")
				.OnPlatform(new OperatingSystemIdentifier());

			var client = new WebSoupClient();
			var updates = await client.CheckForUpdatesAsync(request);

			var availableUpdate = updates.FirstOrDefault();
			if (availableUpdate != null)
			{
				this.Invoke((Action)(() =>
					{
						biUpdate.Visibility = BarItemVisibility.Always;
						biUpdate.Hint = $"Version {availableUpdate.ShortestVersionString} is available.";
						biUpdate.Tag = availableUpdate.Url;
					}));
			}
		}

19 View Source File : HttpConnection.cs
License : MIT License
Project Creator : andruzzzhka

public void BeginReadRequest ()
    {
      if (_buffer == null)
        _buffer = new byte[_bufferLength];

      if (_reuses == 1)
        _timeout = 15000;

      try {
        _timeoutCanceled.Add (_reuses, false);
        _timer.Change (_timeout, Timeout.Infinite);
        _stream.BeginRead (_buffer, 0, _bufferLength, onRead, this);
      }
      catch {
        close ();
      }
    }

19 View Source File : RulePoller.cs
License : Apache License 2.0
Project Creator : aws

internal void Poll(IConnector connector)
        {
            _connector = connector;
            _timer = new Timer(Start);
            _timer.Change(0, 0);
        }

19 View Source File : EmailNotifier.cs
License : MIT License
Project Creator : AiursoftWeb

public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Email notifier service is stopping.");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

19 View Source File : TimerPlugin.cs
License : Apache License 2.0
Project Creator : awslabs

public override void Start()
        {
            //Randomize the first time
            int dueTime = Utility.Random.Next((int)Interval.TotalMilliseconds); //in milliseconds
            _timer.Change(dueTime, (int)Interval.TotalMilliseconds);
        }

19 View Source File : Job2TimedService.cs
License : Apache License 2.0
Project Creator : anjoy8

public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Job 2 is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

19 View Source File : LogSimulator.cs
License : Apache License 2.0
Project Creator : awslabs

public void Start()
        {
            _timer.Change(0, _interval);
        }

19 View Source File : WebSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public void Start()
		{
			if(m_webSocket != null)
				return;

			const string webSocketUrl = "wss://real.okcoin.com:10440/websocket/okcoinapi";

			//set timers
			m_pingTimeoutTimer = new Timer(_ =>
			{
				if (m_pong)
				{
					m_pong = false; //waiting for another ping
				}
				else
				{
					Log.Error("[OKCoin] Ping Timeout!");
					if (TimeoutReceived != null)
					{
						TimeoutReceived(this, new EventArgs());
					}
				}
			}, null, Timeout.Infinite, Timeout.Infinite);

			m_pingIntervalTimer = new Timer(_ =>
			{
				m_webSocket.Send("{'event':'ping'}");
				m_pingTimeoutTimer.Change(PingTimeout, Timeout.Infinite);
				m_pong = false;
			}, null, PingInterval, PingInterval);

			//setup websocket connections and events
			m_webSocket = new WebSocket(webSocketUrl);
			m_webSocket.Opened += btc_Opened;
			m_webSocket.Error += btc_Error;
			m_webSocket.MessageReceived += btc_MessageReceived;
			m_webSocket.DataReceived += btc_DataReceived;
			m_webSocket.Closed += btc_Closed;

			Log.Info("[OKCoin] Opening websockets...");
			m_webSocket.Open();
		}

19 View Source File : TaskbarIcon.cs
License : MIT License
Project Creator : ay2015

public void CloseBalloon()
        {
            if (IsDisposed) return;

            Dispatcher dispatcher = this.GetDispatcher();
            if (!dispatcher.CheckAccess())
            {
                Action action = CloseBalloon;
                dispatcher.Invoke(DispatcherPriority.Normal, action);
                return;
            }

            lock (this)
            {
                //reset timer in any case
                balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);

                //reset old popup, if we still have one
                Popup popup = CustomBalloon;
                if (popup != null)
                {
                    UIElement element = popup.Child;

                    //announce closing
                    RoutedEventArgs eventArgs = RaiseBalloonClosingEvent(element, this);
                    if (!eventArgs.Handled)
                    {
                        //if the event was handled, clear the reference to the popup,
                        //but don't close it - the handling code has to manage this stuff now

                        //close the popup
                        popup.IsOpen = false;

                        //remove the reference of the popup to the balloon in case we want to reuse
                        //the balloon (then added to a new popup)
                        popup.Child = null;

                        //reset attached property
                        if (element != null) SetParentTaskbarIcon(element, null);
                    }

                    //remove custom balloon anyway
                    SetCustomBalloon(null);
                }
            }
        }

19 View Source File : XmlConfigurator.cs
License : Apache License 2.0
Project Creator : apache

private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e)
			{
				LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]");

				// Deliver the event in TimeoutMillis time
				// timer will fire only once
				m_timer.Change(TimeoutMillis, Timeout.Infinite);
			}

19 View Source File : ActorContextExtras.cs
License : Apache License 2.0
Project Creator : asynkron

public void StopReceiveTimeoutTimer() => ReceiveTimeoutTimer?.Change(-1, -1);

19 View Source File : ThreadedAsyncOperation.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

protected void ActivateProgressReport(bool activate)
	{
		try {
			if (activate) {
				progressTimer.Change(0, 50);
				showProgressTimer.Change(500, 0);
			}
			else {
				progressTimer.Change(Timeout.Infinite, Timeout.Infinite);
				showProgressTimer.Change(Timeout.Infinite, Timeout.Infinite);
			}
		}
		catch(ObjectDisposedException) {}
	}

19 View Source File : CachePolicyManager.cs
License : MIT License
Project Creator : Avanade

public void StopFlushTimer()
        {
            lock (_lock)
            {
                _logger?.LogDebug($"{nameof(CachePolicyManager)} flush timer stopped.");
                _timer?.Change(Timeout.Infinite, Timeout.Infinite);
                _timer = null;
            }
        }

19 View Source File : RateGate.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ExitTimerCallback(object state)
        {
            // While there are exit times that are preplaceded due still in the queue,
            // exit the semapreplaced and dequeue the exit time.
            int exitTime;
            while (_exitTimes.TryPeek(out exitTime)
                    && unchecked(exitTime - Environment.TickCount) <= 0)
            {
                _semapreplaced.Release();
                _exitTimes.TryDequeue(out exitTime);
            }

            // Try to get the next exit time from the queue and compute
            // the time until the next check should take place. If the 
            // queue is empty, then no exit times will occur until at least
            // one time unit has preplaceded.
            int timeUntilNextCheck;
            if (_exitTimes.TryPeek(out exitTime))
                timeUntilNextCheck = unchecked(exitTime - Environment.TickCount);
            else
                timeUntilNextCheck = TimeUnitMilliseconds;

            // Set the timer.
            _exitTimer.Change(timeUntilNextCheck, -1);
        }

19 View Source File : AppDelegate.cs
License : MIT License
Project Creator : awaescher

private async void CheckForUpdatesAsync(object state)
		{
			var bundleVersion = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleShortVersionString").ToString();

			var request = new UpdateRequest()
				.WithNameAndVersionFromEntryreplacedembly()
				.WithVersion(bundleVersion)
				.AsAnonymousClient()
				.OnChannel("stable")
				.OnPlatform(new OperatingSystemIdentifier().WithSuffix("(Mac)"));

			var client = new WebSoupClient();
			var updates = await client.CheckForUpdatesAsync(request);

			AvailableUpdate = updates.FirstOrDefault();

			_updateTimer.Change((int)TimeSpan.FromHours(2).TotalMilliseconds, Timeout.Infinite);
		}

19 View Source File : DefaultAutoFetchHandler.cs
License : MIT License
Project Creator : awaescher

private void UpdateBehavior(AutoFetchMode mode)
		{
			var profile = _profiles[mode];

			var milliseconds = (int)profile.PauseBetweenFetches.TotalMilliseconds;
			if (profile.PauseBetweenFetches == TimeSpan.MaxValue)
				milliseconds = Timeout.Infinite;

			_timer.Change(milliseconds, Timeout.Infinite);
		}

19 View Source File : HttpConnection.cs
License : MIT License
Project Creator : andruzzzhka

private static void onRead (IAsyncResult asyncResult)
    {
      var conn = (HttpConnection) asyncResult.AsyncState;
      if (conn._socket == null)
        return;

      lock (conn._sync) {
        if (conn._socket == null)
          return;

        var nread = -1;
        var len = 0;
        try {
          var current = conn._reuses;
          if (!conn._timeoutCanceled[current]) {
            conn._timer.Change (Timeout.Infinite, Timeout.Infinite);
            conn._timeoutCanceled[current] = true;
          }

          nread = conn._stream.EndRead (asyncResult);
          conn._requestBuffer.Write (conn._buffer, 0, nread);
          len = (int) conn._requestBuffer.Length;
        }
        catch (Exception ex) {
          if (conn._requestBuffer != null && conn._requestBuffer.Length > 0) {
            conn.SendError (ex.Message, 400);
            return;
          }

          conn.close ();
          return;
        }

        if (nread <= 0) {
          conn.close ();
          return;
        }

        if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) {
          if (!conn._context.HasError)
            conn._context.Request.FinishInitialization ();

          if (conn._context.HasError) {
            conn.SendError ();
            return;
          }

          HttpListener lsnr;
          if (!conn._listener.TrySearchHttpListener (conn._context.Request.Url, out lsnr)) {
            conn.SendError (null, 404);
            return;
          }

          if (conn._lastListener != lsnr) {
            conn.removeConnection ();
            if (!lsnr.AddConnection (conn)) {
              conn.close ();
              return;
            }

            conn._lastListener = lsnr;
          }

          conn._context.Listener = lsnr;
          if (!conn._context.Authenticate ())
            return;

          if (conn._context.Register ())
            conn._contextRegistered = true;

          return;
        }

        conn._stream.BeginRead (conn._buffer, 0, _bufferLength, onRead, conn);
      }
    }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : awaescher

private async Task CheckForUpdatesAsync()
		{
			var request = new UpdateRequest()
				.WithNameAndVersionFromEntryreplacedembly()
				.AsAnonymousClient()
				.OnChannel("stable")
				.OnPlatform(new OperatingSystemIdentifier().WithSuffix("(WPF)"));

			var client = new WebSoupClient();
			var updates = await client.CheckForUpdatesAsync(request);

			AvailableUpdate = updates.FirstOrDefault();

			_updateTimer.Change((int)TimeSpan.FromHours(2).TotalMilliseconds, Timeout.Infinite);
		}

19 View Source File : TimedCleaner.cs
License : MIT License
Project Creator : AiursoftWeb

public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping.");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

19 View Source File : TargetPoller.cs
License : Apache License 2.0
Project Creator : aws

internal async void Start(Object state)
        {
            try
            {
                await RefreshTargets();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Encountered exception while polling targets");
            }
            finally
            {
                _timer.Change(GetDelay(), 0);
            }
        }

19 View Source File : HttpBase.cs
License : MIT License
Project Creator : andruzzzhka

protected static T Read<T> (Stream stream, Func<string[], T> parser, int millisecondsTimeout)
      where T : HttpBase
    {
      var timeout = false;
      var timer = new Timer (
        state => {
          timeout = true;
          stream.Close ();
        },
        null,
        millisecondsTimeout,
        -1);

      T http = null;
      Exception exception = null;
      try {
        http = parser (readHeaders (stream, _headersMaxLength));
        var contentLen = http.Headers["Content-Length"];
        if (contentLen != null && contentLen.Length > 0)
          http.EnreplacedyBodyData = readEnreplacedyBody (stream, contentLen);
      }
      catch (Exception ex) {
        exception = ex;
      }
      finally {
        timer.Change (-1, -1);
        timer.Dispose ();
      }

      var msg = timeout
                ? "A timeout has occurred while reading an HTTP request/response."
                : exception != null
                  ? "An exception has occurred while reading an HTTP request/response."
                  : null;

      if (msg != null)
        throw new WebSocketException (msg, exception);

      return http;
    }

19 View Source File : RulePoller.cs
License : Apache License 2.0
Project Creator : aws

internal async void Start(Object state)
        {
            try
            {
                await RefreshCache();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Encountered an exception while polling sampling rules.");
            }
            finally
            {
                _timer.Change(GetDelay(), 0); // Next invocation with jitter
            }
        }

19 View Source File : WebSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public void Start()
		{
			if(m_webSocket != null)
				return;

			const string webSocketUrl = "wss://real.okcoin.com:10440/websocket/okcoinapi";

			//set timers
			m_pingTimeoutTimer = new Timer(_ =>
			{
				if (m_pong)
				{
					m_pong = false; //waiting for another ping
				}
				else
				{
					Log.Error("[Huobi] Ping Timeout!");
					if (TimeoutReceived != null)
					{
						TimeoutReceived(this, new EventArgs());
					}
				}
			}, null, Timeout.Infinite, Timeout.Infinite);

			m_pingIntervalTimer = new Timer(_ =>
			{
				m_webSocket.Send("{'event':'ping'}");
				m_pingTimeoutTimer.Change(PingTimeout, Timeout.Infinite);
				m_pong = false;
			}, null, PingInterval, PingInterval);

			//setup websocket connections and events
			m_webSocket = new WebSocket(webSocketUrl);
			m_webSocket.Opened += btc_Opened;
			m_webSocket.Error += btc_Error;
			m_webSocket.MessageReceived += btc_MessageReceived;
			m_webSocket.DataReceived += btc_DataReceived;
			m_webSocket.Closed += btc_Closed;

			Log.Info("[Huobi] Opening websockets...");
			m_webSocket.Open();
		}

19 View Source File : Batch.cs
License : Apache License 2.0
Project Creator : awslabs

private void Flush(FlushReason reason)
        {
            if (_queue.Count > 0)
            {
                _maxTimeSpanTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _onBatch(_queue, _counts, reason);
                Reset();
                if (reason != FlushReason.Stop)
                {
                    _maxTimeSpanTimer.Change((int)_interval.TotalMilliseconds, (int)_interval.TotalMilliseconds);
                }
            }
        }

19 View Source File : Scheduler.cs
License : MIT License
Project Creator : anet-team

public async static Task StopAll()
        {
            if (_issStopping) return;
            _issStopping = true;

            _enabled = false;
            _timer.Change(-1, -1);

            await Task.Run(() =>
            {
                var tasks = new Task[0];
                do
                {
                    lock (_running)
                    {
                        tasks = _running.Select(t => t.Item2).ToArray();
                    }
                    Task.WaitAll(tasks);
                } while (tasks.Any());
                _issStopping = false;
            });
        }

19 View Source File : TimerPlugin.cs
License : Apache License 2.0
Project Creator : awslabs

private void DisableTimer()
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
        }

19 View Source File : BackgroundTaskSample.cs
License : MIT License
Project Creator : AiursoftWeb

public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInfo("Timed Background Service is stopping.");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

19 View Source File : SimpleMetricsSink.cs
License : Apache License 2.0
Project Creator : awslabs

public override void Stop()
        {
            _flushTimer.Change(Timeout.Infinite, Timeout.Infinite);
            if (!_noFlushOnStop)
            {
                Flush(null);
            }
            _logger?.LogInformation("Stopped");
        }

19 View Source File : Job1TimedService.cs
License : Apache License 2.0
Project Creator : anjoy8

public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Job 1 is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

19 View Source File : LogSimulator.cs
License : Apache License 2.0
Project Creator : awslabs

public void Stop()
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
        }

19 View Source File : Edi.cs
License : MIT License
Project Creator : 0ffffffffh

static void DailyClientInfoWiper(object state)
        {
            if (!ediSvc.WipeClientInfos())
            {
                wipeDelayed = true;

                wipeTimer.Change(
                    (int)TimeSpan.FromMinutes(5).TotalMilliseconds,
                    (int)TimeSpan.FromMinutes(5).TotalMilliseconds
                    );

                Log.Warning("Client state wipe cant be done. Will be trying in 5 minutes again");
            }
            else
            {
                if (wipeDelayed)
                {
                    wipeTimer.Change(GetOccurancePeriodInterval(), (int)TimeSpan.FromDays(1).TotalMilliseconds);
                    wipeDelayed = false;
                }

                Log.Info("Client state list wipe successful.");
            }
        }

19 View Source File : TaskbarIcon.cs
License : MIT License
Project Creator : ay2015

public void ResetBalloonCloseTimer()
        {
            if (IsDisposed) return;

            lock (this)
            {
                //reset timer in any case
                balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);
            }
        }

19 View Source File : XmlConfigurator.cs
License : Apache License 2.0
Project Creator : apache

private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e)
			{
				LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]");

				// Deliver the event in TimeoutMillis time
				// timer will fire only once
				m_timer.Change(TimeoutMillis, Timeout.Infinite);
			}

19 View Source File : ShowDesktop.cs
License : MIT License
Project Creator : AlexGyver

private void StartTimer() {
      timer.Change(0, 200);
    }

19 View Source File : Watchdog.cs
License : MIT License
Project Creator : 0ffffffffh

private bool Recalibrate(int ms)
        {
            return workTimer.Change(ms, ms);
        }

19 View Source File : BTCChinaWebSocketApi.cs
License : MIT License
Project Creator : aabiryukov

public void Start()
		{
			if(m_webSocket != null)
				return;

			const string httpScheme = "https://";
			const string wsScheme = "wss://";
			const string webSocketUrl = "websocket.btcc.com/socket.io/";

			#region handshake

			string polling;
			using (var wc = new HttpClient())
			{
				polling = wc.GetStringAsync(httpScheme + webSocketUrl + "?transport=polling").Result;
				if (string.IsNullOrEmpty(polling))
				{
					throw new BTCChinaException("BtcChinaWebSocketApi.Start", "", "failed to download config");
				}
			}

			var config = polling.Substring(polling.IndexOf('{'), polling.IndexOf('}') - polling.IndexOf('{') + 1);
			var wsc = JsonConvert.DeserializeObject<WsConfigHelper>(config);

			#endregion handshake

			//set timers
			m_pingTimeoutTimer = new Timer(_ =>
			{
				if (m_pong)
				{
					m_pong = false; //waiting for another ping
				}
				else
				{
					Log.Error("[BtcChina] Ping Timeout!");
					if (TimeoutReceived != null)
					{
						TimeoutReceived(this, new EventArgs());
					}
				}
			}, null, Timeout.Infinite, Timeout.Infinite);

			m_pingIntervalTimer = new Timer(_ =>
			{
				m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}", (int)EngineioMessageType.PING));
				m_pingTimeoutTimer.Change(wsc.PingTimeout, Timeout.Infinite);
				m_pong = false;
			}, null, wsc.PingInterval, wsc.PingInterval);

			//setup websocket connections and events
			m_webSocket = new WebSocket(wsScheme + webSocketUrl + "?transport=websocket&sid=" + wsc.Sid);
			m_webSocket.Opened += btc_Opened;
			m_webSocket.Error += btc_Error;
			m_webSocket.MessageReceived += btc_MessageReceived;
			m_webSocket.DataReceived += btc_DataReceived;
			m_webSocket.Closed += btc_Closed;

			Log.Info("[BtcChina] Opening websockets...");
			m_webSocket.Open();
		}

19 View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : aglab2

private void UpdateStars(object sender)
        {
            isEmulatorStarted = false;
            isHackLoaded = false;
            isOffsetsFound = false;

            try
            {
                if (um.IsCompleted())
                {
                    if (!isUpdateRequested && !um.IsUpdated())
                    {
                        isUpdateRequested = true;
                        this.SafeInvoke((MethodInvoker)delegate
                        {
                            DialogResult result = MessageBox.Show(String.Format("Update for Star Display available!\n\n{0}\nDo you want to download it now? Press cancel to skip update", um.UpdateName()), "Update",
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                            if (result == DialogResult.Yes)
                            {
                                Process.Start(um.DownloadPath());
                            }
                            if (result == DialogResult.Cancel)
                            {
                                um.WritebackUpdate();
                            }
                        });
                    }
                }
            }
            catch (Exception) { }

            try
            {
                //if (slf != null && slf.sm != null && slf.sm.isServer)
                //    goto bla;

                if (mm.ProcessActive())
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
                
                isEmulatorStarted = true;

                // Well, that's just a minor magic but it works
                if (mm.Getreplacedle().Contains("-"))
                    isHackLoaded = true;

                if (!mm.isMagicDone())
                {
                    if (magicThread == null || !magicThread.IsAlive)
                    {
                        magicThread = new Thread(doMagicThread);
                        magicThread.Start();
                    }

                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); });
                    return;
                }
                
                isOffsetsFound = true;


                try
                {
                    // Just do nothing
                    if (!mm.isReadyToRead())
                        return;

                    mm.PerformRead();
                }
                catch (Exception)
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
 
                bool mmIsInvalidated = mm == null ? false : mm.CheckInvalidated();
                bool gmIsInvalidated = gm == null ? false : gm.CheckInvalidated();
                bool dmIsInvalidated = dm == null ? false : dm.CheckInvalidated();
                bool smIsInvalidated = false;
                if (slf != null && slf.sm != null)
                    smIsInvalidated = slf.sm.CheckInvalidated();

                bool nmIsInvalidated = false;
                if (slf != null && slf.nm != null)
                    nmIsInvalidated = slf.nm.CheckInvalidated();

                if (smIsInvalidated && slf.sm.dropFile)
                {
                    slf.sm.dropFile = false;
                    mm.Stars = new byte[MemoryManager.FileLength];
                    mm.WriteToFile(ld.starsShown);
                    mm.isStarsInvalidated = true;
                }

                if (mmIsInvalidated && mm.isStarsInvalidated)
                {
                    mm.isStarsInvalidated = false;
                    if (slf != null && slf.sm != null)
                    {
                        slf.sm.SendData(mm.Stars);
                    }

                    Console.WriteLine("MM Invalidated!");
                }

                if (gmIsInvalidated)
                    Console.WriteLine("GM Invalidated!");
                if (dmIsInvalidated)
                    Console.WriteLine("DM Invalidated!");

                if (smIsInvalidated)
                {
                    Console.WriteLine("SM Invalidated!");
                    {
                        byte[] stars = slf.sm.AcquiredData;

                        bool shouldSendHelp = false;
                        for (int i = 0; i < stars.Count(); i++)
                        {
                            byte diff = (byte)(mm.Stars[i] ^ stars[i]);
                            if ((mm.Stars[i] & diff) != 0)
                                shouldSendHelp = true;

                            otherStars[i] |= (byte)(diff & stars[i]);
                            mm.Stars[i] = (byte)(mm.Stars[i] | stars[i]);
                        }

                        if (shouldSendHelp)
                        {
                            slf.sm.SendData(mm.Stars);
                        }

                        mm.WriteToFile(ld.starsShown);
                    }
                    if (!mm.IsDecomp)
                    {
                        var location = mm.GetLocation();
                        var netData = slf.sm.getNetData();
                        foreach (var item in netData)
                        {
                            var player = item.Key;
#if DEBUG == false
                            if (player != slf.GetPlayerName())
#endif
                            {
                                var data = item.Value;

                                if (slf is object && slf.nm is object)
                                {
                                    var id = slf.nm.RegisterPlayer(player);
                                    if (data.location == location)
                                        mm.WriteNetState(id, data.state);
                                    else
                                        mm.WriteNetState(id, null);
                                }
                            }
                        }
                    }
                }

                if (nmIsInvalidated)
                {
                    if (!mm.IsDecomp)
                    {
                        mm.WriteNetPatch();
                        var state = mm.GetMarioState();
                        if (slf.sm is object)
                        {
                            slf.sm.SendNet64Data(slf.GetNet64Name(), state, mm.GetLocation());
                        }

                        if (slf.nm.mustReload)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                mm.WriteNetState(i, null);
                            }
                            slf.nm.mustReload = false;
                        }

                        this.SafeInvoke((MethodInvoker)delegate { slf.UpdatePlayers(slf.nm.GetPlayers()); });
                    }
                }

                // We do not draw anything!
                if (!mmIsInvalidated && !gmIsInvalidated && !smIsInvalidated && !dmIsInvalidated)
                {
                    return;
                }

                gm.TestFont();

                if (enableAutoDeleteToolStripMenuItem.Checked)
                {
                    try
                    {
                        mm.DeleteStars();
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Can not modify savefiles. Trying launching with elevated rights!", "Write Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        enableAutoDeleteToolStripMenuItem.Checked = false;
                    }
                }

                //Display stars routine
                baseImage = new Bitmap(starPicture.Width, starPicture.Width * 4);

                Graphics baseGraphics = Graphics.FromImage(baseImage);
                baseGraphics.Clear(Color.Black);
                baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                gm.graphics = Graphics.FromImage(baseImage);

                if (!sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false))
                {
                    TextHighlightAction act = mm.GetCurrentLineAction(ld);
                    if (act != null)
                    {
                        gm.AddLineHighlight(act);
                    }
                }

                UInt16 currentCRC = mm.GetRomCRC();
                if (currentCRC != oldCRC || rm == null || dmIsInvalidated)
                {
                    oldCRC = currentCRC;
                    try
                    {
                        rm = new ROMManager(mm.GetROM());
                        try
                        {
                            if (dm != null)
                            {
                                dm.GetData();
                            }

                            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                            LoadLayoutNoInvalidate(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", false);
                        }
                        catch (IOException)
                        {
                            try
                            {
                                dm = new DownloadManager(rm.GetROMName() + ".jsml");
                            }
                            catch(Exception) { }
                            LoadDefaultLayoutNoInvalidate();
                        }

                        gm.IsFirstCall = true;
                    }
                    catch (IndexOutOfRangeException) //can be generated by box reader
                    { }
                    catch (Exception)
                    { oldCRC = 0; }

                    InvalidateCache();
                }

                int lineOffset = 0;
                var actions = sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false) ?
                    mm.GetCollectablesOnlyDrawActions(ld, rm) : 
                    mm.GetDrawActions(ld, rm, enableLockoutToolStripMenuItem.Checked ? otherStars : null);

                if (actions == null) return;

                foreach (var entry in actions)
                {
                    lineOffset += entry.Execute(gm, lineOffset, sm);
                }
                
                baseGraphics.Dispose();
                this.SafeInvoke(delegate {
                    menuStrip.Enabled = true;
                    starPicture.Image = baseImage;
                    starPicture.Height = (int) (lineOffset * gm.SHeight) + 10;
                    this.Height = (int)(lineOffset * gm.SHeight) + 48;
                });
            }
            catch (Win32Exception)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (NullReferenceException)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (ObjectDisposedException)
            {
            }
            finally
            {
                int period = (isEmulatorStarted && isHackLoaded && isOffsetsFound) ? updatePeriod : scanPeriod;
                timer.Change(period, Timeout.Infinite);
            }
        }

19 View Source File : HttpConnection.cs
License : MIT License
Project Creator : andruzzzhka

private void disposeTimer ()
    {
      if (_timer == null)
        return;

      try {
        _timer.Change (Timeout.Infinite, Timeout.Infinite);
      }
      catch {
      }

      _timer.Dispose ();
      _timer = null;
    }

19 View Source File : DefaultRepositoryMonitor.cs
License : MIT License
Project Creator : awaescher

private void OnRepositoryChangeDetected(Repository repo)
		{
			string path = repo?.Path;

			if (string.IsNullOrEmpty(path))
				return;

			if (_repositoryIgnoreStore.IsIgnored(repo.Path))
				return;

			if (!_repositoryInformationAggregator.HasRepository(path))
			{
				CreateRepositoryObserver(repo, path);

				// use that delay to prevent a lot of sequential writes 
				// when a lot repositories get found in a row
				_storeFlushTimer.Change(5000, Timeout.Infinite);
			}

			OnChangeDetected?.Invoke(this, repo);

			_repositoryInformationAggregator.Add(repo);
		}

See More Examples