public void BeginInvoke(Action action) {
            if(delay == TimeSpan.Zero) {
                BeginInvokeCore(action);
                return;
            }
#if NETFX_CORE
            DispatcherTimer timer = new DispatcherTimer();
#else
            DispatcherTimer timer = new DispatcherTimer(DispatcherPriority, Dispatcher);
#endif
#if NETFX_CORE
            EventHandler<object> onTimerTick = null;
#else
            EventHandler onTimerTick = null;
#endif
            onTimerTick = (s, e) => {
                timer.Tick -= onTimerTick;
                timer.Stop();
                BeginInvokeCore(action);
            };
            timer.Tick += onTimerTick;
            timer.Interval = delay;
            timer.Start();
        }
Пример #2
0
        /// <param name="interval">Timeout in Milliseconds</param>
        /// <param name="action">Action<object> to fire when debounced event fires</object></param>
        /// <param name="optParam">optional parameter</param>
        /// <param name="priority">optional priorty for the dispatcher</param>
        /// <param name="dispatcher">optional dispatcher. If not passed or null CurrentDispatcher is used.</param>
        public void Debounce(int interval,
                             Action <object?> action,
                             object?optParam             = null,
                             DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
                             Dispatcher?dispatcher       = null)
        {
            // kill pending timer and pending ticks
            _timer?.Stop();
            _timer = null;

            dispatcher ??= Dispatcher.CurrentDispatcher;

            // 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 DispatcherTimer(TimeSpan.FromMilliseconds(interval),
                                         priority,
                                         (s, e) =>
            {
                if (_timer == null)
                {
                    return;
                }

                _timer?.Stop();
                _timer = null;
                action.Invoke(optParam);
            },
                                         dispatcher);

            _timer.Start();
        }
        /// <summary>
        /// Evaluates the current filters and applies the filtering to the collection view of the items control.
        /// </summary>
        private void EvaluateFilter()
        {
            _deferFilterEvaluationTimer?.Stop();

            var collectionView = DataGrid.Items;

            // Collect all active filters of all known columns.
            var filteredColumns = GetFilteredColumns();

            if (Filtering != null)
            {
                // Notify client about additional columns being filtered.

                var newColumns = filteredColumns
                                 .Except(_filteredColumns)
                                 .ToArray();

                if (newColumns.Length > 0)
                {
                    var columns = newColumns.ExceptNullItems().ToList().AsReadOnly();
                    var args    = new DataGridFilteringEventArgs(columns);
                    Filtering(DataGrid, args);

                    if (args.Cancel)
                    {
                        return;
                    }
                }

                _filteredColumns = filteredColumns;
            }

            FilterChanged?.Invoke(this, EventArgs.Empty);

            try
            {
                // Apply filter to collection view
                collectionView.Filter = CreatePredicate(filteredColumns);

                // Notify all filters about the change of the collection view.
                foreach (var control in FilterColumnControls)
                {
                    control?.ValuesUpdated();
                }

                var selectedItem = DataGrid.SelectedItem;
                if (selectedItem != null)
                {
                    DataGrid.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => DataGrid.ScrollIntoView(selectedItem)));
                }
            }
            catch (InvalidOperationException)
            {
                // InvalidOperation Exception: "'Filter' is not allowed during an AddNew or EditItem transaction."
                // Grid seems to be still in editing mode, even though we have called DataGrid.CommitEdit().
                // Found no way to fix this by code, but after changing the filter another time by typing text it's OK again!
                // Very strange!
            }
        }
 public override void OnApplyTemplate()
 {
     base.OnApplyTemplate();
     _stopTimer = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Background, (_, _) =>
     {
         _stopTimer?.Stop();
         _isStopping = false;
     }, Dispatcher);
 }
Пример #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ThrottleTimer"/> class.
 /// </summary>
 /// <param name="milliseconds">Milliseconds to throttle.</param>
 /// <param name="handler">The delegate to invoke.</param>
 internal ThrottleTimer(int milliseconds, Action handler)
 {
     Action = handler;
     _throttleTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(milliseconds) };
     _throttleTimer.Tick += (s, e) =>
     {
         _throttleTimer.Stop();
         if (Action != null)
             Action.Invoke();
     };
 }
Пример #6
0
        private void HandleTimerTick(object?sender, EventArgs e)
        {
            if (_timer != null && sender == _timer)
            {
                _timer?.Stop();

                if (_currentStatus == SubtitleStatus.NotShowing)
                {
                    OnSubtitleEvent(SubtitleStatus.Showing, _currentSubtitle?.Text);
                    ConfigureTimer(DateTime.UtcNow - _videoStartTime);
                }
                else
                {
                    OnSubtitleEvent(SubtitleStatus.NotShowing, null);
                    QueueNextSubtitle();
                }
            }
        }
Пример #7
0
        /// <param name="interval">Timeout in Milliseconds</param>
        /// <param name="action">Action<object> to fire when debounced event fires</object></param>
        /// <param name="optParam">optional parameter</param>
        /// <param name="priority">optional priorty for the dispatcher</param>
        /// <param name="dispatcher">optional dispatcher. If not passed or null CurrentDispatcher is used.</param>
        public void Throttle(int interval,
                             Action <object?> action,
                             object?optParam             = null,
                             DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
                             Dispatcher?dispatcher       = null)
        {
            // kill pending timer and pending ticks
            _timer?.Stop();
            _timer = null;

            dispatcher ??= Dispatcher.CurrentDispatcher;

            var curTime = DateTime.UtcNow;

            // if timeout is not up yet - adjust timeout to fire
            // with potentially new Action parameters
            if (curTime.Subtract(_timerStarted).TotalMilliseconds < interval)
            {
                interval -= (int)curTime.Subtract(_timerStarted).TotalMilliseconds;
            }

            _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(interval),
                                         priority,
                                         (s, e) =>
            {
                if (_timer == null)
                {
                    return;
                }

                _timer?.Stop();
                _timer = null;
                action.Invoke(optParam);
            },
                                         dispatcher);

            _timer.Start();
            _timerStarted = curTime;
        }
Пример #8
0
 private void StopTimer()
 {
     _repeatTimer?.Stop();
 }
Пример #9
0
 private void BtnStartStop_OnUnchecked(object sender, RoutedEventArgs e)
 {
     _timer?.Stop();
 }
 /// <summary>
 /// Stops hero image slide show.
 /// </summary>
 public void StopHeroImageSlideShow()
 {
     _heroImageScrollTimer?.Stop();
 }
 private void HandleTypingTimerTimeout(object sender, EventArgs e)
 {
     typingTimer?.Stop();
     RefreshSyntaxVisualizer();
 }
Пример #12
0
        /// <summary>
        /// Waits for the BitmapImage to load.
        /// </summary>
        /// <param name="bitmapImage">The bitmap image.</param>
        /// <param name="timeoutInMs">The timeout in ms.</param>
        /// <returns></returns>
        public static async Task<ExceptionRoutedEventArgs> WaitForLoadedAsync(this BitmapImage bitmapImage, int timeoutInMs = 0)
        {
            var tcs = new TaskCompletionSource<ExceptionRoutedEventArgs>();

            // TODO: NOTE: This returns immediately if the image is already loaded,
            // but if the image already failed to load - the task will never complete and the app might hang.
            if (bitmapImage.PixelWidth > 0 || bitmapImage.PixelHeight > 0)
            {
                tcs.SetResult(null);

                return await tcs.Task;
            }

            //var tc = new TimeoutCheck(bitmapImage);

            // Need to set it to null so that the compiler does not
            // complain about use of unassigned local variable.
            RoutedEventHandler reh = null;
            ExceptionRoutedEventHandler ereh = null;
            EventHandler progressCheckTimerTickHandler = null;
            var progressCheckTimer = new DispatcherTimer();
            Action dismissWatchmen = () =>
            {
                bitmapImage.ImageOpened -= reh;
                bitmapImage.ImageFailed -= ereh;
                progressCheckTimer.Tick -= progressCheckTimerTickHandler;
                progressCheckTimer.Stop();
                //tc.Stop();
            };

            int totalWait = 0;
            progressCheckTimerTickHandler = (sender, o) =>
            {
                totalWait += 10;

                if (bitmapImage.PixelWidth > 0)
                {
                    dismissWatchmen.Invoke();
                    tcs.SetResult(null);
                }
                else if (timeoutInMs > 0 && totalWait >= timeoutInMs)
                {
                    dismissWatchmen.Invoke();
                    tcs.SetResult(null);
                    //ErrorMessage = string.Format("BitmapImage loading timed out after {0}ms for {1}.", totalWait, bitmapImage.UriSource)
                }
            };

            progressCheckTimer.Interval = TimeSpan.FromMilliseconds(10);
            progressCheckTimer.Tick += progressCheckTimerTickHandler;
            progressCheckTimer.Start();
                
            reh = (s, e) =>
            {
                dismissWatchmen.Invoke();
                tcs.SetResult(null);
            };

            ereh = (s, e) =>
            {
                dismissWatchmen.Invoke();
                tcs.SetResult(e);
            };

            bitmapImage.ImageOpened += reh;
            bitmapImage.ImageFailed += ereh;

            return await tcs.Task; 
        }
Пример #13
0
 private void Stop()
 {
     _timer?.Stop();
     Finished = true;
 }
Пример #14
0
 public void Stop()
 {
     timer?.Stop();
     timer = null;
 }
 private void UserControl_Unloaded(object sender, System.Windows.RoutedEventArgs e)
 {
     _timer?.Stop();
     _timer = null;
 }
Пример #16
0
        public LivePreview(string deviceMoniker)
        {
            InitializeComponent();
            photoCollection = (SessionTemplateCollection)(Resources["SessionTemplatePhotos"] as ObjectDataProvider).Data;
            //TODO: Update collection count property based on the selected session template
            //photoCollection.PhotoCount = Get Current Session Template placeholders count.
            // enumerate video devices

            photoCollection.PhotoCount = Settings.CurrentTemplate.Poses.Count;

            // create video source from selected device
            videoSource = new VideoCaptureDevice(deviceMoniker);

            // set NewFrame event handler
            videoSource.NewFrame += delegate(object source, NewFrameEventArgs args)
            {
                try
                {
                    args.Frame.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    var img = (Bitmap)args.Frame.Clone();

                    Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        lastFrame          = BitmapFrame.Create(ToBitmapImage(img));;
                        frameHolder.Source = lastFrame;
                    }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            };

            videoSource.SnapshotFrame += delegate(object source, NewFrameEventArgs args)
            {
                args.Frame.RotateFlip(RotateFlipType.RotateNoneFlipX);
                var img = (Bitmap)args.Frame.Clone();
                lastFrame = BitmapFrame.Create(ToBitmapImage(img));
                UpdateTemplateStackData(lastFrame);
            };

            try
            {
                // start the video source
                videoSource.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            App.Current.Exit += delegate
            {
                videoSource?.SignalToStop();

                dispatcherTimer?.Stop();
            };

            Loaded += delegate
            {
                NavigationService.Navigated += delegate
                {
                    videoSource?.SignalToStop();

                    dispatcherTimer?.Stop();
                };
            };

            if (!string.IsNullOrWhiteSpace(deviceMoniker))
            {
                dispatcherTimer          = new DispatcherTimer();
                dispatcherTimer.Tick    += dispatcherTimer_Tick;
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 500);
                dispatcherTimer.Start();
            }
        }
Пример #17
0
 private void TimerStop() => _timer?.Stop();
Пример #18
0
 public void Stop()
 {
     _timer?.Stop();
     _autoSaveTimer?.Stop();
 }
        private void OnSourceDownloadCompleted(DownloadStringCompletedEventArgs e, VastAdUnit ad, Action<bool> Completed)
        {
#if LATENCYTEST
            var latencySimulatorTimer = new DispatcherTimer();
            latencySimulatorTimer.Interval = TimeSpan.FromSeconds(3);
            latencySimulatorTimer.Start();
            latencySimulatorTimer.Tick += (ts, te) => {
#endif
            if (e.Error == null)
            {
                Exception ex;
                VAST vast;

                if (VAST.Deserialize(e.Result, out vast, out ex) && vast != null)
                {
                    var key = GetAdSourceKey(ad.Source);
                    if (!AvailableAds.ContainsKey(key))
                    {
                        AvailableAds.Add(key, vast);
                    }
                    ad.Vast = vast;

                    if (Completed != null) Completed(true);
                }
                if (ex != null)
                {
                    if (Completed != null) Completed(false);
                }
            }
            else
            {
                //Log.Output(OutputType.Error, "Unknown error handling VAST doc from source url: " + t.Source.uri);
                if (Completed != null) Completed(false);
            }
#if LATENCYTEST
            latencySimulatorTimer.Stop();
        };
#endif
        }
Пример #20
0
 private void closeBalloon()
 {
     _closeTimer?.Stop();
     BalloonPopup.IsOpen = false;
 }
Пример #21
0
 private void StopListening()
 {
     _serverTimer?.Stop();
 }
Пример #22
0
 private void Dt_Tick(object sender, EventArgs e)
 {
     dt?.Stop();
     _Form?.Close();
     // timer.Stop();
 }
Пример #23
0
 public void Dispose()
 {
     vDispatcherTimer?.Stop();
 }
 private void HandleTextViewLostFocus(object sender, EventArgs e)
 {
     _typingTimer?.Stop();
 }
Пример #25
0
 public void Dispose()
 {
     _poller?.Stop();
 }
Пример #26
0
 private void StopTimer() => _timer?.Stop();
Пример #27
0
 public void Stop()
 {
     timer?.Stop();
 }
        /// <summary>
        /// Shows the please wait window using the specific <paramref name="service"/>.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="status">The status.</param>
        private void ShowPleaseWaitWindow(IPleaseWaitService service, string status)
        {
            string determinateFormatString = "Updating item {0} of {1} (" + status + ")";

            const int CounterMax = 25;
            int counter = 0;
            bool isIndeterminate = IsPleaseWaitIndeterminate;

            var dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Tick += (sender, e) =>
                                        {
                                            bool exit = false;

                                            counter++;

                                            if (counter >= CounterMax + 1)
                                            {
                                                exit = true;
                                            }
                                            else if (!isIndeterminate)
                                            {
                                                service.UpdateStatus(counter, CounterMax, determinateFormatString);
                                            }

                                            if (exit)
                                            {
                                                dispatcherTimer.Stop();
                                                service.Hide();
                                            }
                                        };

            if (isIndeterminate)
            {
                service.Show(status);
            }
            else
            {
                service.UpdateStatus(1, CounterMax, determinateFormatString);
            }

            dispatcherTimer.Start();
        }
Пример #29
0
 private void Filter_TextChanged(object sender, TextChangedEventArgs e)
 {
     FilterTimer?.Stop();
     FilterTimer?.Start();
 }
Пример #30
0
 private void StopTimer()
 {
     _timer?.Stop();
     _timer = null;
 }
Пример #31
0
 void StopGame()
 {
     isStarted        = false;
     btnStart.Content = "Start";
     dispatcherTimer?.Stop();
 }
Пример #32
0
 private void grid_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
 {
     _timer?.Stop();
 }
Пример #33
0
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     _timer?.Stop();
 }
 void StopScrolling()
 {
     dispatcherTimer?.Stop();
     dispatcherTimer = null;
 }
Пример #35
0
 public void StopTimer()
 {
     _timer?.Stop();
     IsAnimationRunning = false;
 }