Dispose() public method

public Dispose ( ) : void
return void
Beispiel #1
0
        public void Close()
        {
            IsActive = false;
            StateChanged?.Invoke();

            _timer?.Dispose();
        }
Beispiel #2
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation(@"Startup Leader Elector for operator ""{operatorName}"".", _settings.Name);

            _leaseCheck?.Dispose();
            _leaseCheck = new Timer(
                TimeSpan.FromSeconds(_settings.LeaderElectionCheckInterval).TotalMilliseconds)
            {
                AutoReset = true,
            };

            _logger.LogTrace("Fetching namespace for leader election.");
            _namespace = await _client.GetCurrentNamespace();

            _operatorDeployment = (await _client.List <V1Deployment>(
                                       _namespace,
                                       new EqualsSelector("operator-deployment", _settings.Name))).FirstOrDefault();
            if (_operatorDeployment != null)
            {
                _operatorDeployment.Kind       = V1Deployment.KubeKind;
                _operatorDeployment.ApiVersion = $"{V1Deployment.KubeGroup}/{V1Deployment.KubeApiVersion}";
            }

#if DEBUG
            _election.LeadershipChanged(LeaderState.Leader);
#else
            _leaseCheck.Start();
            _leaseCheck.Elapsed += async(_, __) => await CheckLeaderLease();

            await CheckLeaderLease();
#endif
        }
Beispiel #3
0
        /// <summary>
        /// Close the Producer.
        /// </summary>
        public void Close()
        {
            if (_closed)
            {
                return;
            }

            lock (_closeLock)
            {
                if (_closed)
                {
                    return;
                }

                _logger.LogDebug($"Close() | Producer:{ProducerId}");

                _closed = true;

                _checkConsumersTimer?.Dispose();

                // Remove notification subscriptions.
                _channel.MessageEvent -= OnChannelMessage;
                //_payloadChannel.MessageEvent -= OnPayloadChannelMessage;

                // Fire and forget
                _channel.RequestAsync(MethodId.PRODUCER_CLOSE, _internal).ContinueWithOnFaultedHandleLog(_logger);

                Emit("@close");

                // Emit observer event.
                Observer.Emit("close");
            }
        }
        /// <summary>
        /// Debounce reset timer and after last item received give you last item.
        /// </summary>
        /// <param name="obj">Your object</param>
        /// <param name="interval">Milisecond interval</param>
        /// <param name="debounceAction">Called when last item call this method and after interval was finished</param>
        public static void Debounce(object?obj, int interval, Action <object> debounceAction)
        {
            _lastObjectDebounce = obj;
            _debounceAction     = debounceAction;

            _debounceTimerInterval?.Dispose();

            _debounceTimerInterval = new Timer(DebounceTimerIntervalOnTick, obj, interval, interval);
        }
Beispiel #5
0
        void ProcessResendRequest(Message request)
        {
            _testRequestTimer?.Dispose();
            _testRequestTimer = null;

            int beginSeqNo = request.BeginSeqNo;
            int endSeqNo   = request.EndSeqNo;

            PerformResend(beginSeqNo, endSeqNo);
        }
Beispiel #6
0
        /// <summary>
        /// Debounce reset timer and after last item recieved give you last item.
        /// <exception cref="http://demo.nimius.net/debounce_throttle/">See this example for understanding what is RateLimiting and Debounce</exception>
        /// </summary>
        /// <param name="obj">Your object</param>
        /// <param name="interval">Milisecond interval</param>
        /// <param name="debounceAction">Called when last item call this method and after interval was finished</param>
        public void Debounce <T>(int interval, Action <T> action, [AllowNull] T param)
        {
            _timer?.Dispose();
            _timer = new Timer(state =>
            {
                _timer !.Dispose();
                if (_timer != null)
                {
#pragma warning disable CS8604 // Possible null reference argument.
                    action.Invoke(param);
#pragma warning restore CS8604 // Possible null reference argument.
                }

                _timer = null;
            }, param, interval, interval);
        }
    static void Main()
        {
            // Create an event to signal the timeout count threshold in the 
            // timer callback.
            AutoResetEvent autoEvent     = new AutoResetEvent(false);

            StatusChecker  statusChecker = new StatusChecker(10);

            // Create an inferred delegate that invokes methods for the timer.
            TimerCallback tcb = statusChecker.CheckStatus;

            // Create a timer that signals the delegate to invoke  
            // CheckStatus after one second, and every 1/4 second  
            // thereafter.
            Console.WriteLine("{0} Creating timer.\n", 
                              DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

            // When autoEvent signals, change the period to every 
            // 1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");

            // When autoEvent signals the second time, dispose of  
            // the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
        protected override void ExecutionLoop(IAsyncResult result)
        {
            icon = new NotifyIcon();
            timer = new Timer();
            icons = new Icon[4];

            for (int i = 0; i < 4; i++)
            {
                icons[i] = (Icon) GetResourceObject( (i + 1).ToString());
            }

            icon.Icon = icons[currentIconIndex];
            icon.Text = GetResourceString("IconTip");
            icon.Visible = true;
            icon.DoubleClick += OnIconDoubleClick;

            timer.Tick += OnTimerTick;
            timer.Interval = 350;
            timer.Start();

            Application.Run();

            icon.Dispose();
            timer.Dispose();
        }
        public async Task Debounce(int interval, Func <Task> action)
        {
            // kill pending timer and pending ticks
            if (timer is not null)
            {
                await timer.DisposeAsync();
            }

            timer = null;

            // timer is recreated for each event and effectively
            // resets the timeout. Action only fires after timeout has fully
            // elapsed without other events firing in between
            timer = new Timer(
                async(_) =>
            {
                if (timer == null)
                {
                    return;
                }

                timer?.Dispose();
                timer = null;
                await action.Invoke();
            },
                null,
                TimeSpan.FromMilliseconds(interval),
                Timeout.InfiniteTimeSpan);
        }
Beispiel #10
0
 private void RunUntil(object?state)
 {
     StopMotor(PortLeft);
     StopMotor(PortRight);
     _timer?.Dispose();
     _timer = null;
 }
Beispiel #11
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _timer?.Dispose();
     }
 }
Beispiel #12
0
        /// <summary>
        /// Clean up can be called by:
        /// 1. The user. AsyncUnaryCall.Dispose et al will call this on Dispose
        /// 2. <see cref="ValidateHeaders"/> will call dispose if errors fail validation
        /// 3. <see cref="FinishResponseAndCleanUp"/> will call dispose
        /// </summary>
        private void Cleanup(Status status)
        {
            if (!ResponseFinished)
            {
                // If the response is not finished then cancel any pending actions:
                // 1. Call HttpClient.SendAsync
                // 2. Response Stream.ReadAsync
                // 3. Client stream
                //    - Getting the Stream from the Request.HttpContent
                //    - Holding the Request.HttpContent.SerializeToStream open
                //    - Writing to the client stream
                CancelCall(status);
            }
            else
            {
                _callTcs.TrySetResult(status);

                ClientStreamWriter?.WriteStreamTcs.TrySetCanceled();
                ClientStreamWriter?.CompleteTcs.TrySetCanceled();
                ClientStreamReader?.HttpResponseTcs.TrySetCanceled();
            }

            _ctsRegistration?.Dispose();
            _deadlineTimer?.Dispose();
            HttpResponse?.Dispose();
            ClientStreamReader?.Dispose();
            ClientStreamWriter?.Dispose();

            // To avoid racing with Dispose, skip disposing the call CTS.
            // This avoid Dispose potentially calling cancel on a disposed CTS.
            // The call CTS is not exposed externally and all dependent registrations
            // are cleaned up.
        }
Beispiel #13
0
        public static void Main(string[] args)
        {
            int tickCount = 0;
            //sample callback which does the work you want.
            Action callback = () => { tickCount++; };

            // perform work after a specfic interval
            TimeSpan interval = TimeSpan.FromMilliseconds(1);

            //instatiate the timer
            var timer = new Timer(callback, interval);

            //start it
            timer.Start();

            //wait and give some room for processing
            Thread.Sleep(20);

            timer.Stop();
            timer.Dispose();

            //tick count should be ~20-23
            Console.WriteLine("Tick Count => {0}", tickCount);

            // keep result window open to see the result
            Thread.Sleep(2000);
        }
Beispiel #14
0
        protected virtual void Dispose(bool isDisposing)
        {
            _StopHandle.Set();

            _LogMessageProcessingThread.Join();

            if (isDisposing)
            {
                _Timer?.Dispose();
                _LogFileManager.Dispose();
                _OptionsReloadToken.Dispose();
                _StopHandle.Dispose();
                _ArchiveNowHandle.Dispose();
                _MessageReadyHandle.Dispose();
            }
        }
 public void Timer_Change_UInt32_Int64_AfterDispose_Throws()
 {
     var t = new Timer(EmptyTimerTarget);
     t.Dispose();
     Assert.Throws<ObjectDisposedException>(() => t.Change(0u, 0u));
     Assert.Throws<ObjectDisposedException>(() => t.Change(0L, 0L));
 }
		public void Collapse(bool silent = false)
		{
			if (silent || AnimationDelay == 0)
			{
				Width = pnClosed.Width;
				pnOpened.Visible = false;
				pnClosed.Visible = true;
			}
			else
			{
				var timer = new Timer();
				timer.Interval = AnimationDelay > ContentSize ? AnimationDelay / ContentSize : 100;
				timer.Tick += (o, e) =>
				{
					if (Width > (pnClosed.Width + 50))
						Width -= 50;
					else
					{
						Width = pnClosed.Width;
						pnOpened.Visible = false;
						pnClosed.Visible = true;
						timer.Stop();
						timer.Dispose();
						timer = null;
					}
					Application.DoEvents();
				};
				timer.Start();
			}
			if (!silent)
				StateChanged?.Invoke(this, new StateChangedEventArgs(false));
		}
        /// <summary>
        /// Override this method and dispose any objects you own the lifetime of if disposing is true.
        /// </summary>
        /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                _disposed = true;
                _logger.LogDebug("Disposing instance.");

                _rebroadcastAliveNotificationsTimer?.Dispose();
                _rebroadcastAliveNotificationsTimer = null;

                _networkManager.NetworkChanged -= NetworkChanged;
                DlnaServerPlugin.Instance !.ConfigurationChanging -= UpdateConfiguration;

                var tasks = Devices.ToList().Select(RemoveDevice).ToArray();
                Task.WaitAll(tasks);

                // Must be last, or there won't be any sockets available.
                Server.DeleteEvent("M-SEARCH", RequestReceived);
            }

            _disposed = true;
        }
        public async Task DebounceAsync <T>(TimeSpan interval, Action <T> action, T param)
        {
            await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

            _timer?.Dispose();
            _timer = null;
            _timer = new Timer(
                async s =>
            {
                await _semaphoreSlim.WaitAsync().ConfigureAwait(true);
                if (_timer == null)
                {
                    _semaphoreSlim.Release();
                    return;
                }

                _timer?.Dispose();
                _timer = null;
                _semaphoreSlim.Release();
                ExecuteAction(action, param);
            },
                null,
                interval,
                TimeSpan.FromMilliseconds(-1));
            _semaphoreSlim.Release();
        }
Beispiel #19
0
        public void Dispose()
        {
            lock (_work)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
                _timer?.Dispose();
                _timer = null;
                _work.Clear();
                _disposalCts.Cancel();
                _disposalCts.Dispose();
            }
        }
Beispiel #20
0
        public async Task DisposeTest()
        {
            int callCount = 0;

            //Run the timer for a second, then change it, and run it for another second to get a total count
            //Expect 9 iterations
            Timer timer = new Timer((s) => callCount++, null, 100, 100);
            await Task.Delay(1000);

            //Expect no more iterations
            timer.Dispose();
            int lastCallCount = callCount;
            await Task.Delay(1000);

            timer.Dispose();
            Assert.AreEqual(lastCallCount, callCount, "Timer continued to fire after being stopped");
        }
Beispiel #21
0
 // Internal so it can be overridden in tests
 internal virtual void StopCleanupTimer()
 {
     lock (_cleanupTimerLock)
     {
         _cleanupTimer?.Dispose();
         _cleanupTimer = null;
     }
 }
Beispiel #22
0
 public void Dispose()
 {
     _peerRefreshQueue?.Dispose();
     _refreshLoopCancellation?.Dispose();
     _refreshLoopTask?.Dispose();
     _signals?.Dispose();
     _upgradeTimer?.Dispose();
 }
 public override bool ShowDataSourceSelector()
 {
     Timer t = new Timer();
     t.Interval = 5;
     t.Tick += (s, e) => { t.Stop(); t.Dispose(); t = null; ShowDataSeriesConfig(); };
     t.Start();
     return true;
 }
Beispiel #24
0
 public void Dispose()
 {
     _Timer?.Dispose();
     _Timer = null;
     _stringWriterRedirect?.Dispose();
     _stringWriterRedirect = null;
     _stringReaderRedirect?.Dispose();
     _stringReaderRedirect = null;
 }
 /// <inheritdoc />
 public void Dispose()
 {
     _initialiseTokenSrc.Cancel();
     _modConfigService.Items.CollectionChanged -= OnGetModifications;
     _refreshProcessesWithLoaderTimer?.Dispose();
     _instanceTracker.OnProcessesChanged -= OnProcessesChanged;
     _instanceTracker.Dispose();
     GC.SuppressFinalize(this);
 }
Beispiel #26
0
        void FadeOut()
        {
            if (InFadeOut)
                return;

            if (SystemInformation.TerminalServerSession)
            {
                if (Startup)
                    Application.ExitThread();

                StressForm = null;
                base.Close();
                return;
            }

            int duration = 500;//in milliseconds
            int steps = 50;
            Timer timer = new Timer();
            timer.Interval = duration / steps;
            timer.Enabled = true;

            int currentStep = steps;
            timer.Tick += (arg1, arg2) =>
            {
                Opacity = ((double)currentStep) / steps;
                currentStep--;

                if (currentStep <= 0)
                {
                    timer.Stop();
                    timer.Dispose();

                    if (Startup)
                        Application.ExitThread();

                    Visible = false;

                    if (StressForm != null && StressForm.Visible)
                        StressForm.Invoke(new Action(() =>
                        {
                            if (StressForm != null)
                            {
                                StressForm.TopMost = true;
                                Application.DoEvents();
                                StressForm.TopMost = false;
                            }
                        }));

                    StressForm = null;
                    base.Close();

                }
            };

            timer.Start();
        }
Beispiel #27
0
        internal void Shutdown()
        {
            _state = State.ShuttingDown;

            // deactivate timer callbacks
            Timer?t = _cleanupTimer;

            _cleanupTimer = null;
            t?.Dispose();
        }
        /// <summary>
        ///     Disposes the underlying timer.
        /// </summary>
        /// <exception cref="ObjectDisposedException">thrown if the instance is disposed</exception>
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            _timer?.Dispose();
        }
 void IDisposable.Dispose()
 {
     _editTimer?.Dispose();
     _editTimer = null;
     if (PageCriteria != null)
     {
         PageCriteria.PageChanged     -= PageCriteria_PageChanged;
         PageCriteria.PageSizeChanged -= PageCriteria_PageSizeChanged;
     }
 }
Beispiel #30
0
 public void BiometricsLogin()
 {
     var context = new LAContext();
     NSError AuthError;
     var myReason = new NSString(LoginScreenData.BioLoginMessage);
     if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
     {
         var replyHandler = new LAContextReplyHandler((success, error) =>
         {
             this.InvokeOnMainThread(() =>
             {
                 if (success)
                 {
                     var obj = Global.DatabaseManager.GetUsername();
                     var pwd = Encrypt.DecryptString(obj.PWD);
                     Dictionary<string, string> parameters = new Dictionary<string, string>();
                     parameters.Add("username", obj.Username);
                     parameters.Add("password", pwd);
                     parameters.Add("app_device_number", Device.DeviceID);
                     loginScreenView.Hide();
                     initLoadingScreenView(LoginScreenData.LoadingScreenTextLogin);
                     atimer = new Timer(1000);
                     atimer.Elapsed += (s, e) =>
                     {
                         if (ServerURLReady)
                         {
                             InvokeOnMainThread(() =>
                             {
                                 LoginWebCall(parameters);
                                 atimer.Stop();
                                 atimer.Dispose();
                             });
                         }
                     };
                     atimer.AutoReset = true;
                     atimer.Enabled = true;
                 }
                 else if (error!=null && error.ToString().Contains("Application retry limit exceeded")){
                     //Show fallback mechanism here
                     new UIAlertView(LoginScreenData.AlertScreenBioLoginFailTitle,
                                     error.ToString()+" "+LoginScreenData.AlertScreenBioLoginFaildMessage,
                                     null, LoginScreenData.AlertScreenBioLoginFaildCancelBtnTitle, null).Show();
                 }
                 PWDLogin();
             });
         });
         context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
     }
     else {
         loginScreenView.userNameTextField.Hidden = false;
         loginScreenView.passwordTextField.Hidden = false;
         loginScreenView.loginBtn.Hidden = false;
         loginScreenView.fingerPrintView.Hidden = true;
     }
 }
Beispiel #31
0
        private void ErrorCallback(object?state)
        {
            _errorOccurred = false;
            _waitHandles.ErrorEvent.Reset();

            // the error state is cleaned, destroy the timer to avoid periodic invocation
            Timer?t = _errorTimer;

            _errorTimer = null;
            t?.Dispose(); // Cancel timer request.
        }
Beispiel #32
0
 private void InitTimer()
 {
     _timer = new Timer();
     _timer.Interval = 1;
     _timer.Tick += (o, e) =>
     {
         SetBrowser();
         _timer.Stop();
         _timer.Dispose();
     };
 }
Beispiel #33
0
        void IDisposable.Dispose()
        {
            lock (_lockObj)
            {
                _disposed = true;

                _timer?.Dispose();

                _timer = null;
            }
        }
 public void Dispose()
 {
     _isDisposed = true;
     _timer?.Dispose();
     _requests.Writer.TryComplete();
     Flush();
     _output.Finish();
     _cancellationTokenSource.Cancel();
     _cancellationTokenSource.Dispose();
     _task.Dispose();
 }
Beispiel #35
0
        /// <summary>
        /// Handler for releasing the button.
        /// </summary>
        protected void HandleButtonReleased()
        {
            if (_debounceTime.Ticks > 0 && !IsPressed)
            {
                return;
            }

            _debounceStartTicks = DateTime.UtcNow.Ticks;
            _holdingTimer?.Dispose();
            _holdingTimer = null;

            IsPressed = false;

            ButtonUp?.Invoke(this, new EventArgs());
            Press?.Invoke(this, new EventArgs());

            if (IsHoldingEnabled && _holdingState == ButtonHoldingState.Started)
            {
                _holdingState = ButtonHoldingState.Completed;
                Holding?.Invoke(this, new ButtonHoldingEventArgs {
                    HoldingState = ButtonHoldingState.Completed
                });
            }

            if (IsDoublePressEnabled)
            {
                if (_lastPress == DateTime.MinValue.Ticks)
                {
                    _lastPress = DateTime.UtcNow.Ticks;
                }
                else
                {
                    if (DateTime.UtcNow.Ticks - _lastPress <= _doublePressTicks)
                    {
                        DoublePress?.Invoke(this, new EventArgs());
                    }

                    _lastPress = DateTime.MinValue.Ticks;
                }
            }
        }
Beispiel #36
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _timer?.Dispose();

                _cancellationCts?.Cancel();
                _cancellationCts?.Dispose();

                _semaphoreSlim?.Dispose();
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _timer?.Dispose();
                }

                _disposedValue = true;
            }
        }
Beispiel #38
0
 public void Dispose()
 {
     _logger.LogTrace("Disposing SQLite cache database at {SqliteCacheDbPath}", _config.CachePath);
     _cleanupTimer?.Dispose();
     Commands?.Dispose();
     if (_db is not null)
     {
         _logger.LogTrace("Closing connection to SQLite database at {SqliteCacheDbPath}", _config.CachePath);
         _db.Close();
         _db.Dispose();
     }
 }
Beispiel #39
0
    public static int Main(string[] args)
    {
        Thread th = new Thread(new ThreadStart(Thread2));
        th.Start();
        Thread th2 = new Thread(new ThreadStart(Thread3));
        th2.Start();

        for (int i = 0; i < 20000 && !_fTestFailed; i++)
        {
            _mre = new ManualResetEvent(false);
            Timer t = new Timer(new TimerCallback(callback), null, 1000000, Timeout.Infinite);
            _are.Set();

			bool bDisposeSucceeded = false; //Used to improve speed of the test when Dispose has failed
			try
			{
				t.Dispose();
				bDisposeSucceeded = true;
			}
			catch (ObjectDisposedException)
			{
			}

			if (bDisposeSucceeded)
			{
				try
				{
					if (_mre.WaitOne(0))
					{
						Console.Write("@");
					}
				}
				catch (ObjectDisposedException)
				{
				}
			}
        }
        _fTestDone = true;
		_are.Set();
        th.Join();
        th2.Join();

		if (!_fTestFailed)
		{
			Console.WriteLine("Test Passed");
			return 100;
		}

		Console.WriteLine("Test Failed");
		return 101;

    }
Beispiel #40
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             StopMulticast();
             MulticastTimer?.Dispose();
             Multicaster?.Dispose();
         }
         disposedValue = true;
     }
 }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation(@"Startup Leader Elector for operator ""{operatorName}"".", _settings.Name);

            _leaseCheck?.Dispose();
            _leaseCheck = new Timer(
                TimeSpan.FromSeconds(_settings.LeaderElectionCheckInterval).TotalMilliseconds)
            {
                AutoReset = true,
            };

#if DEBUG
            _election.LeadershipChanged(LeaderState.Leader);

            return(Task.CompletedTask);
#else
            _leaseCheck.Start();
            _leaseCheck.Elapsed += async(_, __) => await CheckLeaderLease();

            return(CheckLeaderLease());
#endif
        }
 public static void ShowPopup(MailScreen parent, string newBlockedUser)
 {
     Timer timer = new Timer {
         Interval = 30
     };
     timer.Tick += new EventHandler(MailUserBlockPopup.tooltipCallbackFunction);
     timer.Tag = "0";
     timer.Enabled = true;
     MailUserBlockPopup popup = new MailUserBlockPopup();
     popup.init(parent, newBlockedUser);
     popup.ShowDialog(InterfaceMgr.Instance.ParentForm);
     popup.Dispose();
     timer.Stop();
     timer.Dispose();
 }
Beispiel #43
0
        public async Task ChangeTest()
        {
            int callCount = 0;

            //Run the timer for a second, then change it, and run it for another second to get a total count
            //Expect 9 iterations
            Timer timer = new Timer((s) => callCount++, null, 100, 100);
            await Task.Delay(1000);

            //Expect 4 iterations
            timer.Change(200, 200);
            await Task.Delay(1000);

            timer.Dispose();
            Assert.AreEqual(13, callCount, "Callcount was incorrect");
        }
Beispiel #44
0
        public void RefreshGrid2()
        {
            ///
            /// a criacao de um timer foi um arremedo que fiz para que o municipio seja excluido da grade
            /// tentei excluir diretamente ou dar um rebuild, mas este componente dá um erro de recursividade.
            /// 
            timerRefresh = new Timer();
            timerRefresh.Tick += delegate
            {
                timerRefresh.Stop();
                timerRefresh.Dispose();

                this.grid2.RefreshMunicipiosDefinidos();
            };
            timerRefresh.Start();
        }
 public BrowseSamplesForm()
 {
     this.InitializeComponent();
     this.webBrowser.DocumentStream = new MemoryStream(Encoding.UTF8.GetBytes("Connecting..."));
     this.webBrowser.Navigating += new WebBrowserNavigatingEventHandler(this.webBrowser_Navigating);
     this.EnableControls();
     base.Icon = Resources.LINQPad;
     Timer tmr = new Timer();
     tmr.Tick += delegate (object sender, EventArgs e) {
         if (!this.IsDisposed)
         {
             this.webBrowser.Navigate("http://www.linqpad.net/RichClient/SampleLibraries.aspx");
         }
         tmr.Dispose();
     };
     tmr.Start();
 }
Beispiel #46
0
 private void AboutForm_Shown(object sender, EventArgs e)
 {
     var timer = new Timer
     {
         Interval = 1,
         Enabled = true
     };
     timer.Tick += (o, args) =>
     {
         if (Opacity < 1d)
         {
             Opacity += .1d;
             return;
         }
         timer.Dispose();
     };
 }
		private static void Slide(Toast slice) {

			int targetY = slice.Top + slice.Height;
			Timer timer = new Timer() {
				Interval = 10
			};

			timer.Tick += delegate(object sender, EventArgs args) {
				slice.Top = Math.Min(slice.Top + 10, targetY);

				if (slice.Top == targetY) {
					timer.Stop();
					timer.Dispose();
				}
			};

			timer.Start();
		}
Beispiel #48
0
	public static int Main()
	{
		TestLibrary.TestFramework.BeginTestCase("Timer.Dispose()");

		TestLibrary.TestFramework.BeginScenario("Timer.Dispose() hang test");
		TestLibrary.TestFramework.LogInformation("Creating timercallback");
		TimerCallback tcb = new TimerCallback(Target);

		TestLibrary.TestFramework.LogInformation("Creating timer");
		Timer timer = new Timer(tcb,null,0,0);
	
		TestLibrary.TestFramework.LogInformation("Calling timer.Dispose");
		timer.Dispose();

		TestLibrary.TestFramework.EndTestCase();
		TestLibrary.TestFramework.LogInformation("PASS");

		return 100;
	}
Beispiel #49
0
        private void setupFadeIn() {
            int duration = 1000;//in milliseconds
            int steps = 100;
            Timer timer = new Timer();
            timer.Interval = duration / steps;

            int currentStep = 0;
            timer.Tick += (arg1, arg2) => {
                Opacity = ((double)currentStep) / steps;
                currentStep++;
                if (currentStep >= steps) {
                    timer.Stop();
                    timer.Dispose();
                    complete = true;
                }
            };

            timer.Start();
        }
        /// <summary>Creates a Task that will complete after the specified delay.</summary>
        /// <param name="factory">The TaskFactory.</param>
        /// <param name="millisecondsDelay">The delay after which the Task should transition to RanToCompletion.</param>
        /// <param name="cancellationToken">The cancellation token that can be used to cancel the timed task.</param>
        /// <returns>A Task that will be completed after the specified duration and that's cancelable with the specified token.</returns>
        public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken)
        {
            // Validate arguments
            if (factory == null) throw new ArgumentNullException("factory");
            if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay");

            // Check for a pre-canceled token
            if (cancellationToken.IsCancellationRequested)
                return factory.FromCancellation(cancellationToken);

            // Create the timed task
            var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
            var ctr = default(CancellationTokenRegistration);

            // Create the timer but don't start it yet.  If we start it now,
            // it might fire before ctr has been set to the right registration.
            var timer = new Timer(self =>
            {
                // Clean up both the cancellation token and the timer, and try to transition to completed
                ctr.Dispose();
                ((Timer)self).Dispose();
                tcs.TrySetResult(null);
            });

            // Register with the cancellation token.
            if (cancellationToken.CanBeCanceled)
            {
                // When cancellation occurs, cancel the timer and try to transition to canceled.
                // There could be a race, but it's benign.
                ctr = cancellationToken.Register(() =>
                {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            // Start the timer and hand back the task...
            try { timer.Change(millisecondsDelay, Timeout.Infinite); }
            catch(ObjectDisposedException) {} // in case there's a race with cancellation; this is benign

            return tcs.Task;
        }
Beispiel #51
0
        public SqlParseResult Parse(string input)
        {
            var result = new SqlParseResult(Dialect);

            var timer = new Timer();

            try {
                long time;
                var node = ParseNode(input, result.Errors, out time);
                result.RootNode = node;
            } catch (Exception ex) {
                // TODO: form a better exception
                result.Errors.Add(new SqlParseError(ex.Message, 0, 0));
            } finally {
                timer.Dispose();
                result.ParseTime = timer.Elapsed;
            }

            return result;
        }
Beispiel #52
0
		async void WBLoaderShown(object sender, EventArgs e)
		{
			this.WindowState = FormWindowState.Minimized;
			this.WindowState = FormWindowState.Normal;
			this.BringToFront();
			int duration = 1000;//in milliseconds
		    int steps = 100; 
		    Timer timer = new Timer();
		    timer.Interval = duration / steps;
			
		    int currentStep = 0;
		    timer.Tick += (arg1, arg2) =>
		    {
		        Opacity = ((double)currentStep) / steps;
		        currentStep++;
		
		        if (currentStep >= steps)
		        {
		            timer.Stop();
		            timer.Dispose();
		        }
		    };
		
		    timer.Start();
			var t = Task.Run(()=>PulseLogo());
			SetStatus("R E A D I N G");
			await Task.Delay(2000);
			
			/*
			#if DEBUG
			LoadBXB();
			#else
			var t2 = Task.Run(()=>LoadBXB());
			await t2;
			#endif
			*/
			var t2 = Task.Run(()=>LoadBXB());
			await t2;
			
			await t;
		}
        public AboutBox()
        {
            InitializeComponent();

            this.Icon = Resources.zss_main;
            Bitmap bmp = Resources.main;
            bmp = ColorMatrices.ApplyColorMatrix(bmp, ColorMatrices.InverseFilter());
            bmp = ColorMatrices.ApplyColorMatrix(bmp, ColorMatrices.SaturationFilter(-250));
            pbLogo.Image = bmp;
            this.Text = String.Format("About {0}", AssemblyTitle);
            this.labelProductName.Text = AssemblyProduct;
            this.labelVersion.Text = String.Format("Version {0}", Application.ProductVersion);
            this.lblRev.Location = new Point(this.labelVersion.Left + this.labelVersion.Width + 10, this.labelVersion.Top);
            this.lblRev.Text = string.Format("Rev. {0}", Adapter.AppRevision);
            this.labelCopyright.Text = AssemblyCopyright;
            lblDevelopers.Text = string.Format("{0} is developed by:", AssemblyTitle);
            Timer timer = new Timer { Interval = 100 };
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            this.FormClosing += (v1, v2) => timer.Dispose();
        }
 public void Timer_Dispose_WaitHandle()
 {
     int tickCount = 0;
     var someTicksPending = new ManualResetEvent(false);
     var completeTicks = new ManualResetEvent(false);
     var allTicksCompleted = new ManualResetEvent(false);
     var t =
         new Timer(s =>
         {
             if (Interlocked.Increment(ref tickCount) == 2)
                 someTicksPending.Set();
             Assert.True(completeTicks.WaitOne(MaxPositiveTimeoutInMs));
             Interlocked.Decrement(ref tickCount);
         }, null, 0, 1);
     Assert.True(someTicksPending.WaitOne(MaxPositiveTimeoutInMs));
     completeTicks.Set();
     t.Dispose(allTicksCompleted);
     Assert.True(allTicksCompleted.WaitOne(MaxPositiveTimeoutInMs));
     Assert.Equal(0, tickCount);
     Assert.Throws<ObjectDisposedException>(() => t.Change(0, 0));
 }
Beispiel #55
0
        void FadeAway()
        {
            int duration = 1000;//in milliseconds
            int steps = 100;
            Timer timer = new Timer();
            timer.Interval = duration / steps;

            int currentStep = 0;
            timer.Tick += (arg1, arg2) =>
            {
                Opacity = 1 - ((double)currentStep) / steps;
                currentStep++;

                if (currentStep >= steps)
                {
                    timer.Stop();
                    timer.Dispose();
                    this.Hide();
                }
            };
            timer.Start();
        }
Beispiel #56
0
 public static int Main()
 {
     int retVal = 0;
     Timer timer = new Timer(new TimerCallback(Target),new Object(), 1000,1000);
     timer.Dispose();
     try
     {
         timer.Change(5000,5000);
         retVal = -5;
     }
     catch(ObjectDisposedException)
     {
         Console.WriteLine("Caught Expected exception");
         retVal = 100;
     }
     catch(Exception ex)
     {
         Console.WriteLine("Unexpected exception: " + ex.ToString());
         retVal = -1;
     }
     Console.WriteLine(100 == retVal ? "Test Passed":"Test Failed");
     return retVal;
 }
Beispiel #57
0
        /// <summary>
        /// Método para animación de opacado al inicio de la aplicación. El Form
        /// afectado y sus componentes pasan de una opacidad mínima a su opacidad
        /// total (transición de this.Opacity de 0.0d a 1.0d en una serie de pasos)
        /// </summary>
        private void opacarForm()
        {
            int duracion = 200; // en milisegundos
            int pasos = 30;
            Timer timer = new Timer();
            timer.Interval = duracion / pasos;

            int pasoActual = 0;
            timer.Tick += (arg1, arg2) =>
            {
                // Calcular una fracción para configurar la opacidad gradualmente
                Opacity = ((double) pasoActual) / pasos;
                pasoActual++;

                if (pasoActual >= pasos)
                {
                    timer.Stop();
                    timer.Dispose();
                }
            };

            timer.Start();
        }
Beispiel #58
0
        void FadeIn()
        {
            this.Show();
            this.WindowState = FormWindowState.Minimized;
            this.WindowState = FormWindowState.Normal;
            int duration = 1000;//in milliseconds
            int steps = 100;
            Timer timer = new Timer();
            timer.Interval = duration / steps;

            int currentStep = 0;
            timer.Tick += (arg1, arg2) =>
            {
                Opacity = ((double)currentStep) / steps;
                currentStep++;

                if (currentStep >= steps)
                {
                    timer.Stop();
                    timer.Dispose();
                }
            };
            timer.Start();
        }
Beispiel #59
0
            static void SafeSetClipboard(object dataObject)
            {
                // Work around ExternalException bug. (SD2-426)
                // Best reproducable inside Virtual PC.
                int version = unchecked(++_safeSetClipboardDataVersion);

                try
                {
                    Clipboard.SetDataObject(dataObject, true);
                }
                catch (ExternalException)
                {
                    var timer = new Timer();
                    timer.Interval = 100;
                    timer.Tick += delegate
                    {
                        timer.Stop();
                        timer.Dispose();

                        if (_safeSetClipboardDataVersion != version)
                            return;

                        try
                        {
                            Clipboard.SetDataObject(dataObject, true, 10, 50);
                        }
                        catch (ExternalException)
                        {
                        }
                    };

                    timer.Start();
                }
            }
Beispiel #60
0
        internal void InsertSnippet(Snippet snip, int startPos)
        {
            NativeScintilla.BeginUndoAction();
            IsActive = false;

            string snippet = snip.RealCode;

            //	First properly indent the template. We do this by
            //	getting the indent string of the current line and
            //	adding it to all newlines
            int indentPoint = 0;
            string line = Scintilla.Lines.Current.Text;
            if(line != string.Empty)
            {				
                while (indentPoint < line.Length)
                {
                    char c = line[indentPoint];
                    if (c != ' ' && c != '\t')
                        break;

                    indentPoint++;
                }
            }

            //	Grab the current selected text in case we have a surrounds with scenario.
            string selText = Scintilla.Selection.Text;
            //	Now we clear the selection
            if (selText != string.Empty)
                Scintilla.Selection.Clear();

            if (indentPoint > 0)
            {
                string indent = line.Substring(0, indentPoint);

                //	This is a bit of a tough decision, but I think the best way to handle it
                //	is to assume that the Snippet's Eol Marker matches the Platform DOCUMENT_DEFAULT
                //	but the target Eol Marker should match the Document's.
                snippet = snippet.Replace(Environment.NewLine, Scintilla.EndOfLine.EolString + indent);

                //	Same deal with the selected text if any				
                selText = selText.Replace(Environment.NewLine, Scintilla.EndOfLine.EolString + indent);
            }

            int anchorPos = -1;
            int caretPos = -1;
            int endPos = -1;
            int selPos = -1;
            SortedList<int, int> dropMarkers = new SortedList<int, int>();
            SortedList<int, SnippetLinkRange> indexedRangesToActivate = new SortedList<int, SnippetLinkRange>();
            List<SnippetLinkRange> unindexedRangesToActivate = new List<SnippetLinkRange>();
            Match m = snippetRegex1.Match(snippet);

            while (m.Success)
            {
                //	Did it match a $DropMarker$ token?
                if (m.Groups["dm"].Success)
                {
                    //	Yep, was it an indexed or unindexed DropMarker
                    if (m.Groups["dmi"].Success)
                    {
                        //	Indexed, set the indexed drop marker's character offset
                        //	if it is specified more than once the last one wins.
                        dropMarkers[int.Parse(m.Groups["dmi"].Value)] = m.Groups["dm"].Index;
                    }
                    else
                    {
                        //	Unindexed, just tack it on at the _end
                        dropMarkers[dropMarkers.Count] = m.Groups["dm"].Index;
                    }

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["dm"].Index, m.Groups["dm"].Length);
                }
                else if (m.Groups["c"].Success)
                {
                    //	We matched the $Caret$ Token. Since there can be 
                    //	only 1 we set the caretPos. If this is specified
                    //	more than once the last one wins
                    caretPos = m.Groups["c"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["c"].Index, m.Groups["c"].Length);
                }
                else if (m.Groups["a"].Success)
                {
                    //	We matched the $Anchor$ Token. Since there can be 
                    //	only 1 we set the anchorPos. If this is specified
                    //	more than once the last one wins
                    anchorPos = m.Groups["a"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["a"].Index, m.Groups["a"].Length);
                }
                else if (m.Groups["e"].Success)
                {
                    //	We matched the $End$ Token. Since there can be 
                    //	only 1 we set the endPos. If this is specified
                    //	more than once the last one wins
                    endPos = m.Groups["e"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["e"].Index, m.Groups["e"].Length);
                }
                else if (m.Groups["s"].Success)
                {
                    //	We matched the $Selection$ Token. Simply insert the
                    //	selected text at this position
                    selPos = m.Groups["s"].Index;

                    //	Take the token out of the string
                    snippet = snippet.Remove(m.Groups["s"].Index, m.Groups["s"].Length);
                    snippet = snippet.Insert(m.Groups["s"].Index, selText);
                }
                else if (m.Groups["l"].Success)
                {
                    //	Finally match for Snippet Link Ranges. This is at the bottom of the if/else
                    //	because we want the more specific regex groups to match first so that this
                    //	generic expression group doesn't create a SnippetLinkRange for say the 
                    //	$Caret$ Token.
                    Group g = m.Groups["l"];

                    int rangeIndex;
                    string groupKey;

                    if (m.Groups["li"].Success)
                    {
                        //	We have a subindexed SnippetLinkRange along the lines of $sometoken[1]$
                        Group sg = m.Groups["li"];

                        //	At this point g.Value = $sometoken[1]$
                        //	and sg.Value = [1].
                        //	We want the range's Key, which would be sometoken
                        groupKey = g.Value.Substring(1, g.Value.Length - sg.Length - 2);

                        //	Now we need the range's Index which would be 1 in our fictitional case
                        rangeIndex = int.Parse(sg.Value.Substring(1, sg.Value.Length - 2));

                        //	Now we need to determine the actual _start and _end positions of the range.
                        //	Keep in mind we'll be stripping out the 2 $ and the subindex string (eg [1])
                        int start = startPos + g.Index;
                        int end = start + g.Length - sg.Length - 2;

                        //	And now we add (or replace) the snippet link range at the index
                        //	keep in mind duplicates will stomp all over each other, the last
                        //	one wins. Replaced tokens won't get a range
                        indexedRangesToActivate[rangeIndex] = new SnippetLinkRange(start, end, Scintilla, groupKey); ;

                        //	And remove all the token info including the subindex from the snippet text 
                        //	leaving only the key
                        snippet = snippet.Remove(g.Index, 1).Remove(g.Index - 2 + g.Length - sg.Length, sg.Length + 1);
                    }
                    else
                    {
                        //	We have a regular old SnippetLinkRange along the lines of $sometoken$

                        //	We want the range's Key, which would be sometoken
                        groupKey = g.Value.Substring(1, g.Value.Length - 2);

                        //	Now we need to determine the actual _start and _end positions of the range.
                        //	Keep in mind we'll be stripping out the 2 $
                        int start = startPos + g.Index;
                        int end = start + g.Length - 2;

                        //	Now create the range object
                        unindexedRangesToActivate.Add(new SnippetLinkRange(start, end, Scintilla, groupKey));

                        //	And remove all the token info from the snippet text 
                        //	leaving only the key
                        snippet = snippet.Remove(g.Index, 1).Remove(g.Index + g.Length - 2, 1);
                    }
                }
                //	Any more matches? Note that I'm rerunning the regexp query
                //	on the snippet string becuase it's contents have been modified
                //	and we need to get the updated index values.
                m = snippetRegex1.Match(snippet);
            }

            //	Replace the snippet Keyword with the snippet text. Or if this
            //	isn't triggered by a shortcut, it will insert at the current
            //	Caret Position
            Scintilla.GetRange(startPos, NativeScintilla.GetCurrentPos()).Text = snippet;

            //	Now that we have the text set we can activate our link ranges
            //	we couldn't do it before becuase they were managed ranges and
            //	would get offset by the text change

            //	Since we are done adding new SnippetLinkRanges we can tack
            //	on the unindexed ranges to the _end of the indexed ranges
            SnippetLinkRange[] allLinks = new SnippetLinkRange[indexedRangesToActivate.Count + unindexedRangesToActivate.Count];
            for (int i = 0; i < indexedRangesToActivate.Values.Count; i++)
                allLinks[i] = indexedRangesToActivate[i];

            for (int i = 0; i < unindexedRangesToActivate.Count; i++)
                allLinks[i + indexedRangesToActivate.Count] = unindexedRangesToActivate[i];

            foreach (SnippetLinkRange slr in allLinks)
                addSnippetLink(slr);

            foreach (SnippetLinkRange slr in allLinks)
                slr.Init();

            //	Now we need to activate the Snippet links. However we have a bit
            //	of a styling confilct. If we set the indicator styles before the
            //	SQL Lexer styles the newly added text it won't get styled. So to
            //	make sure we set the Indicator Styles after we put the call on
            //	a timer.
            if (_snippetLinks.Count > 0)
            {
                Timer t = new Timer();
                t.Interval = 10;

                //	Oh how I love anonymous delegates, this is starting to remind
                //	me of JavaScript and SetTimeout...
                t.Tick += new EventHandler(delegate(object sender, EventArgs te)
                {
                    t.Dispose();
                    IsActive = true;
                });
                t.Start();
            }

            //	Add all the Drop markers in the indexed order. The
            //	order is reversed of course because drop markers work
            //	in a FILO manner
            for (int i = dropMarkers.Count - 1; i >= 0; i--)
                Scintilla.DropMarkers.Drop(startPos + dropMarkers.Values[i]);

            //	Place the caret at either the position of the token or
            //	at the _end of the snippet text.
            if (caretPos >= 0)
                Scintilla.Caret.Goto(startPos + caretPos);
            else
                Scintilla.Caret.Goto(startPos + snippet.Length);

            //	Ahoy, way anchor!
            if (anchorPos >= 0)
                Scintilla.Caret.Anchor = startPos + anchorPos;

            //	Do we have an _end cursor?
            if (endPos >= 0)
            {
                //	If they have snippet link ranges activated in this snippet
                //	go ahead and set up an EndPoint marker
                if (allLinks.Length > 0)
                {
                    SnippetLinkEnd eci = new SnippetLinkEnd(endPos + startPos, Scintilla);
                    Scintilla.ManagedRanges.Add(eci);
                    _snippetLinks.EndPoint = eci;
                }
                else
                {
                    //	Otherwise we treat it like an Anchor command because
                    //	the SnippetLink mode isn't activated
                    Scintilla.Caret.Goto(endPos + startPos);
                }
            }

            NativeScintilla.EndUndoAction();
        }