Example #1
0
        private void SocketListener_stopStreaming(object sender, string args)
        {
            StationLib.StationSocketListener SocketListener = sender as StationLib.StationSocketListener;
            if (args.Length > 0)
            {
                if (SocketListener != null)
                {
                    ThreadPoolTimer timer = ThreadPoolTimer.CreateTimer((t) =>
                    {
                        SocketListener.stopProcessingPackagesAsync();// Restart Processing Packages
                        SocketListener.startProcessingPackagesAsync();
                        //do some work \ dispatch to UI thread as needed
                    }, TimeSpan.FromSeconds(20));
                }


                if (SocketListener.FailedConnectionCount <= 1)
                {
                    ShowMessage(args);
                    notificationEmail(SocketListener, args);
                }
            }

            ReleaseDisplay(SocketListener);
        }
Example #2
0
        private static void DelayAction(int timeout, CancellationToken cancellationToken, Action action)
        {
            if (timeout == Timeout.Infinite)
            {
                return;
            }

            var reg = default(CancellationTokenRegistration);

#if WIN_RT
            var timer = ThreadPoolTimer.CreateTimer(
                _ =>
            {
                reg.Dispose();
                action();
            },
                TimeSpan.FromMilliseconds(timeout)
                );
            reg = cancellationToken.Register(timer.Cancel);
#else
            var timer = new Timer(
                _ =>
            {
                reg.Dispose();
                action();
            },
                null, timeout, Timeout.Infinite
                );
            reg = cancellationToken.Register(timer.Dispose);
#endif
        }
Example #3
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral

            _deferral = taskInstance.GetDeferral();

            await Task.Delay(30000);

            bs = new RateSensor();
            bs.RateSensorInit();

            await Task.Delay(1000);

            bs.RateMonitorON();

            deviceWatcher = DeviceInformation.CreateWatcher(
                "System.ItemNameDisplay:~~\"Adafruit\"",
                new string[] {
                "System.Devices.Aep.DeviceAddress",
                "System.Devices.Aep.IsConnected"
            },
                DeviceInformationKind.AssociationEndpoint);

            deviceWatcher.Added   += DeviceWatcher_Added;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            deviceWatcher.Start();

            // NFC
            proxDevice = ProximityDevice.GetDefault();
            if (proxDevice != null)
            {
                proxDevice.SubscribeForMessage("NDEF", messagedReceived);
            }
            else
            {
                Debug.WriteLine("No proximity device found\n");
            }

            this.timer = ThreadPoolTimer.CreateTimer(Timer_Tick, TimeSpan.FromSeconds(2));

            try
            {
                await Task.Run(async() =>
                {
                    while (true)
                    {
                        await Task.Delay(100000);
                    }
                });
            }
            catch (Exception ex)
            {
            }
            deviceWatcher.Stop();
        }
Example #4
0
        public void OnWindowSizeChanged(object sender, WindowSizeChangedEventArgs e)
        {
            if (m_timer != null)
            {
                m_timer.Cancel();
                m_timer = null;
            }
            TimeSpan period = TimeSpan.FromSeconds(1.0);

            m_timer = ThreadPoolTimer.CreateTimer(async(source) => {
                if (!resized_already_)
                {
                    await page_.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                        if (!resized_already_)
                        {
                            resized_already_ = true;
                            ApplicationView.GetForCurrentView().TryResizeView(new Windows.Foundation.Size {
                                Width = 500, Height = 840
                            });
                            m_timer.Cancel();
                        }
                    });
                }
                else
                {
                    m_timer.Cancel();
                }
            }, period);
        }
        /// <summary>
        /// Initiate Enumeration with specific RemoteSystemKind with Filters
        /// </summary>
        private async void GenerateSystemsWithFilterAsync(List <IRemoteSystemFilter> filter)
        {
            var accessStatus = await RemoteSystem.RequestAccessAsync();

            if (accessStatus == RemoteSystemAccessStatus.Allowed)
            {
                _remoteSystemWatcher = filter != null?RemoteSystem.CreateWatcher(filter) : RemoteSystem.CreateWatcher();

                _remoteSystemWatcher.RemoteSystemAdded   += RemoteSystemWatcher_RemoteSystemAdded;
                _remoteSystemWatcher.RemoteSystemRemoved += RemoteSystemWatcher_RemoteSystemRemoved;
                _remoteSystemWatcher.RemoteSystemUpdated += RemoteSystemWatcher_RemoteSystemUpdated;
                if (ApiInformation.IsEventPresent("Windows.System.RemoteSystems.RemoteSystemWatcher", "EnumerationCompleted"))
                {
                    _remoteSystemWatcher.EnumerationCompleted += RemoteSystemWatcher_EnumerationCompleted;
                }
                else
                {
                    ThreadPoolTimer.CreateTimer(
                        (e) =>
                    {
                        RemoteSystemWatcher_EnumerationCompleted(_remoteSystemWatcher, null);
                    }, TimeSpan.FromSeconds(2));
                }

                _remoteSystemWatcher.Start();
            }
        }
Example #6
0
        /// <summary>
        /// Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.
        /// </summary>
        /// <param name="dueTime">
        /// The amount of time to delay before the invoking the callback method specified when the Timer was constructed, in milliseconds. Specify Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.
        /// </param>
        /// <param name="period">
        /// The time interval between invocations of the callback method specified when the Timer was constructed, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.
        /// </param>
        /// <returns>true if the timer was successfully updated; otherwise, false.</returns>
        public bool Change(int dueTime, int period)
        {
            if (dueTime < -1)
            {
                throw new ArgumentOutOfRangeException("dueTime", "NeedNonNegOrNegative1");
            }

            if (period < -1)
            {
                throw new ArgumentOutOfRangeException("period", "NeedNonNegOrNegative1");
            }

            if (threadPoolTimer != null)
            {
                threadPoolTimer.Cancel();
                threadPoolTimer = null;
            }

            if (dueTime == Timeout.Infinite)
            {
                // If dueTime is Infinite, the callback method is never invoked; the timer is disabled
                return(true);
            }
            else if (dueTime == 0)
            {
                // If dueTime is zero (0), the callback method is invoked immediately
                StartTimers(period);
            }
            else
            {
                ThreadPoolTimer.CreateTimer(timer => this.StartTimers(period), TimeSpan.FromMilliseconds(dueTime), timer => timer.Cancel());
            }

            return(true);
        }
Example #7
0
        private async void LoadData()
        {
            // hide splash screen after 2 seconds
            ThreadPoolTimer.CreateTimer(SplashTimeOut, new TimeSpan(0, 0, 2));

            this.recentDS = new LatestPostsDS();
            this.recentDS.DataRequestError    += recentDS_DataRequestError;
            this.recentDS.OnLoadMoreCompleted += recentDS_OnLoadMoreCompleted;
            this.lv_HomePosts.ItemsSource      = this.recentDS;
            this.tb_HomeTag.DataContext        = this.recentDS;

            this.topViewDS = new DataHelper.CloudAPI.TwoDaysTopViewPostsDS();
            this.topViewDS.DataRequestError += recentDS_DataRequestError;
            this.lv_HotPosts.ItemsSource     = this.topViewDS;
            this.tb_HotTag.DataContext       = this.topViewDS;

            this.topLikeDS = new TenDaysTopLikePostsDS();
            this.topLikeDS.DataRequestError += recentDS_DataRequestError;
            this.lv_BestPosts.ItemsSource    = this.topLikeDS;
            this.tb_BestTag.DataContext      = this.topLikeDS;

            this.topBloggerDS = new RecommendBloggerDS();
            this.topBloggerDS.DataRequestError += recentDS_DataRequestError;
            this.lv_Bloggers.ItemsSource        = this.topBloggerDS.Bloggers;
            await topBloggerDS.LoadRemoteData();

            this.newsDs = new NewsDS();
            this.newsDs.DataRequestError += recentDS_DataRequestError;
            this.lv_News.ItemsSource      = this.newsDs;
            this.tb_NewsTag.DataContext   = this.newsDs;
        }
Example #8
0
        //The Closed event handler
        private void WebSock_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
        {
            WSLOG("WS: disconnenction detected");
            _connected = false;
            foreach (Queue <WSRequest> queue in _workingRequests)
            {
                foreach (WSRequest wsRequest in queue)
                {
                    wsRequest.imm_close(YAPI.IO_ERROR, "Websocket connection lost with " + _hub.Host);
                }

                queue.Clear();
            }

            if (!_mustStop)
            {
                _hub._devListValidity = 500;
                int error_delay = 100 << (_notifRetryCount > 4 ? 4 : _notifRetryCount);
                _notifRetryCount++;
                TimeSpan delay = TimeSpan.FromMilliseconds(error_delay);
                _reconnectionTimer = ThreadPoolTimer.CreateTimer(expirationHandler, delay);
            }

            WSLOG("WS: disconnenction detected done");
        }
Example #9
0
 public static void StartAppUpdateChecker(TimeSpan timeSpan)
 {
     if (_appUpdateCheckTimer == null)
     {
         _appUpdateCheckTimer = ThreadPoolTimer.CreateTimer(AppUpdateCheck, timeSpan);
     }
 }
Example #10
0
        public void timerOn()
        {
            _TimerOfProgressValue = ThreadPoolTimer.CreatePeriodicTimer(
                async(source) =>
            {
                await progressBar.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () =>
                {
                    if (CurrentValueOfProgressBar >= 0)
                    {
                        CurrentValueOfProgressBar -= Tools.REFERSHINTERVAL;
                    }
                }
                    );
            }, TimeSpan.FromMilliseconds(Tools.REFERSHINTERVAL));



            _TimerOfLost = ThreadPoolTimer.CreateTimer(
                async(source) =>
            {
                await progressBar.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    async() =>
                {
                    await CallGameLostContentDiagAsync();
                }
                    );
            },
                TimeSpan.FromMilliseconds(currentMaxValueOfProgressBar));
        }
Example #11
0
        private void StartRefreshTimer()
        {
            TimeSpan delay     = TimeSpan.FromHours(3);
            bool     completed = false;

            weatherLoadTimer = ThreadPoolTimer.CreateTimer((s) =>
            {
                ViewPageModel.WeatherViewModel.GetWeatherItems();

                Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    ViewPageModel.WeatherViewModel.RefreshWeaherItems();
                });

                completed = true;
            }, delay, (s) =>
            {
                // TODO: 작업 취소 / 완료 처리하기
                Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    if (completed)
                    {
                        // 타이머가 완료되었을 때
                    }
                    else
                    {
                        // 타이머가 취소되었을 때
                    }
                });
            });
        }
Example #12
0
 void Transport_onStatus(ConnectionStatus status, ConnectionErrors error, string errorMsg)
 {
     this.connStatus = status;
     if (onStatus != null)
     {
         if (WebErrorStatus.ConnectionAborted.ToString().Equals(errorMsg))
         {
             if (this.shouldConnect)
             {
                 onStatus(status, error, errorMsg + " " + ErrorMessage.reconnIn5s);
             }
             else
             {
                 onStatus(status, error, errorMsg);
             }
             ThreadPoolTimer timer = ThreadPoolTimer.CreateTimer(
                 async(obj) =>
             {
                 await ThreadPool.RunAsync(TryToConnectDisconnect, WorkItemPriority.High);
             }, new TimeSpan(0, 0, 0, 0, 5000));
         }
         else
         {
             onStatus(status, error, errorMsg);
             if (error == ConnectionErrors.AUTH_FAILED)
             {
                 this.shouldConnect = false;
             }
         }
     }
     else
     {
         throw new ArgumentNullException("Error: " + this.GetType() + " require a StatusEventHandler onStatus");
     }
 }
Example #13
0
        /// <summary>
        /// Update the UI if the user has resized the window.
        /// At this point, the window is resized to the minimum size if the user resizes it too small.
        /// This is considered VERY bad behaviour.
        /// TODO: Make the UI properly responsive.
        /// </summary>
        /// <param name="sender">CoreWindow</param>
        /// <param name="e">WindowSizeChangedEventArgs containing the new window size</param>
        public void UpdateUI(CoreWindow sender, WindowSizeChangedEventArgs e)
        {
            // Check if the timer is already running.
            // If so, then cancel it. It will be re-created below if the window is still too small.
            if (windowResizeTimer != null)
            {
                windowResizeTimer.Cancel();
            }

            // Get the new window width and height.
            double newHeight = e.Size.Height;
            double newWidth  = e.Size.Width;

            // Check if the window is too narrow.
            if ((newWidth < this.minWindowWidth) || (newHeight < this.minWindowHeight))
            {
                // Set the timeout to 1 second.
                TimeSpan timeout = new TimeSpan(0, 0, 0, 1);

                // Create a new timer. After the timeout, the resize code will be executed.
                windowResizeTimer = ThreadPoolTimer.CreateTimer(async(ThreadPoolTimer timer) =>
                {
                    await this.globalEventHandlerInstance.controllerDispatcher.RunAsync(
                        CoreDispatcherPriority.Normal, () =>
                    {
                        ApplicationView.GetForCurrentView().TryResizeView(new Size(this.minWindowWidth, this.minWindowHeight));
                    });
                }, timeout);
            }
        }
Example #14
0
        private void SetTimer()
        {
            var  t  = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TimerTime);
            long tt = 0;

            if (t != null)
            {
                tt = (long)t;
            }

            TimeSpan currentTime      = TimeSpan.FromHours(DateTime.Now.Hour) + TimeSpan.FromMinutes(DateTime.Now.Minute) + TimeSpan.FromSeconds(DateTime.Now.Second);
            long     currentTimeTicks = currentTime.Ticks;

            TimeSpan delay = TimeSpan.FromTicks(tt - currentTimeTicks);

            if (delay > TimeSpan.Zero)
            {
                if (timerIsSet)
                {
                    TimerCancel();
                }
                timer      = ThreadPoolTimer.CreateTimer(new TimerElapsedHandler(TimerCallback), delay);
                timerIsSet = true;
            }
        }
Example #15
0
        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (_threadPooTimer != null)
            {
                _threadPooTimer.Cancel();
                _threadPooTimer = null;
            }
            TimeSpan period = TimeSpan.FromSeconds(1.0);

            _threadPooTimer = ThreadPoolTimer.CreateTimer(async(source) =>
            {
                if (!_hasBeenResized)
                {
                    await _page.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        if (!_hasBeenResized)
                        {
                            _hasBeenResized = true;
                            ApplicationView.GetForCurrentView().TryResizeView(e.NewSize);
                            _threadPooTimer.Cancel();
                        }
                    });
                }
                else
                {
                    _threadPooTimer.Cancel();
                }
            }, period);
        }
        public void Connect(HTransportOptions options)
        {
            this.connStatus = ConnectionStatus.CONNECTING;
            this.options    = options;

            //TODO init the connection timeout value!!
            connTimeout = new TimeSpan(0, 0, 0, 0, options.Timeout);

            string endpointHost = options.EndpointHost;
            int    endpointPort = options.EndpointPort;
            string endpointPath = options.EndpointPath;

            string endpointAdress = ToEndpointAdress(endpointHost, endpointPort, endpointPath);

            connTimeoutTimer = ThreadPoolTimer.CreateTimer(timeout_Elapsed, connTimeout);

            socketIO = new Client(endpointAdress);

            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;
            socketIO.On("connect", (message) =>
            {
                if (this.options.AuthCb != null)
                {
                    this.options.AuthCb(options.Login, Login);
                }
                else
                {
                    Login(options.Login, options.Password);
                }
            });
            socketIO.ConnectAsync();
        }
Example #17
0
 private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
 {
     if (AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile")
     {
         if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
         {
             if (DelayTimer != null && DelayTimer.Delay != TimeSpan.Zero)
             {
                 DelayTimer.Cancel();
             }
             TimeSpan delay = TimeSpan.FromMilliseconds(1000);
             DelayTimer = ThreadPoolTimer.CreateTimer(
                 async(source) =>
             {
                 await Dispatcher.RunAsync(
                     CoreDispatcherPriority.High,
                     () =>
                 {
                     ViewModel.GetSearchSuggestions();
                 });
             },
                 delay);
         }
     }
 }
Example #18
0
        /// <summary>
        /// Detect faces and process them
        /// </summary>
        /// <param name="timer"></param>
        private async void ProcessCurrentVideoFrameAsync(ThreadPoolTimer timer)
        {
            // fill the frame
            await _mediaCapture.GetPreviewFrameAsync(_previewFrame);

            // collection for faces
            IList <DetectedFace> faces;

            if (FaceDetector.IsBitmapPixelFormatSupported(_previewFrame.SoftwareBitmap.BitmapPixelFormat))
            {
                // get detected faces on the frame
                faces = await _faceTracker.ProcessNextFrameAsync(_previewFrame);
            }
            else
            {
                throw new NotSupportedException($"PixelFormat {BitmapPixelFormat.Nv12} is not supported by FaceDetector.");
            }

            // get the size of frame webcam provided, we need it to scale image on the screen
            var previewFrameSize = new Size(_previewFrame.SoftwareBitmap.PixelWidth, _previewFrame.SoftwareBitmap.PixelHeight);

            ProcessFrameFaces(previewFrameSize, faces);

            // arrange the next processing time
            ThreadPoolTimer.CreateTimer(ProcessCurrentVideoFrameAsync, _frameProcessingTimerInterval);
        }
Example #19
0
        private void XamlCodeRenderer_KeyDown(Monaco.CodeEditor sender, Monaco.Helpers.WebKeyEventArgs args)
        {
            // Handle Shortcuts.
            // Ctrl+Enter or F5 Update // TODO: Do we need this in the app handler too? (Thinking no)
            if ((args.KeyCode == 13 && args.CtrlKey) ||
                args.KeyCode == 116)
            {
                var t = UpdateXamlRenderAsync(XamlCodeRenderer.Text);

                // Eat key stroke
                args.Handled = true;
            }

            // Ignore as a change to the document if we handle it as a shortcut above or it's a special char.
            if (!args.Handled && Array.IndexOf(NonCharacterCodes, args.KeyCode) == -1)
            {
                // TODO: Mark Dirty here if we want to prevent overwrites.

                // Setup Time for Auto-Compile
                this._autocompileTimer?.Cancel(); // Stop Old Timer

                // Create Compile Timer
                this._autocompileTimer = ThreadPoolTimer.CreateTimer(
                    async(e) =>
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        var t = UpdateXamlRenderAsync(XamlCodeRenderer.Text);
                    });
                }, TimeSpan.FromSeconds(0.5));
            }
        }
Example #20
0
 private void Submit_Button_Click(object sender, RoutedEventArgs e) //user submit his input
 {
     _ = input.StringDealAsync();                                   //transform the input into reverse polish notation and judge the legality of input
     if (input.GetandSetArray != null)
     {
         _ = solve.Judge(input.CaculationResult, input.GetandSetArray);//judge the caculation result of RPN and modify the value of solve.Correct
     }
     if (solve.Correct == true)
     {
         user.Wintimes++;
         solve.Correct = false;
         ChangeImage();   //in the function solve.Judge if result is correct, it will invoke ProduceRandomNumber
     }
     if (--PlayTime <= 0) //every submit will cost one play chance
     {
         bool jump = true;
         _timer = ThreadPoolTimer.CreateTimer(
             (timer) =>
         {
             jump = false;
         },
             TimeSpan.FromSeconds(2));
         while (jump)
         {
             ;
         }
         Frame.Navigate(typeof(GradePage), user);//the function that need to delay
     }
 }
        private async void ProcessResults(Face[] faces, Emotion[] emotions, SoftwareBitmap swbitmap)
        {
            if (faces != null || swbitmap != null)
            {
                try
                {
                    WriteableBitmap bitmap = new WriteableBitmap(swbitmap.PixelWidth, swbitmap.PixelHeight);
                    swbitmap.CopyToBuffer(bitmap.PixelBuffer);

                    List <FaceWithEmotions> result = new List <FaceWithEmotions>();
                    foreach (Face person in faces)
                    {
                        _seenAlready.Add(person.FaceId);
                        Emotion personEmotion  = null;
                        int     currentMinimum = 65000;
                        if (emotions != null)
                        {
                            foreach (Emotion emo in emotions)
                            {
                                int diff = RectIntersectDifference(person.FaceRectangle, emo.FaceRectangle);
                                if (diff < currentMinimum)
                                {
                                    currentMinimum = diff;
                                    personEmotion  = emo;
                                }
                            }
                        }

                        WriteableBitmap img = await CropAsync(bitmap, IncreaseSize(person.FaceRectangle, bitmap.PixelHeight, bitmap.PixelWidth));

                        result.Add(new FaceWithEmotions(person, personEmotion, img));
                    }

                    while (_seenAlready.Count > 10)
                    {
                        _seenAlready.RemoveAt(0);
                    }

                    DetectedFaces?.Invoke(result.ToArray());
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("ProcessResults exception : " + ex.Message);
                }
            }

            //_processingFace = false;

            // to avoid asking too many queries, the limit is 20 per minute
            // lets have a quick break after each query
            if (_threadPoolTimer == null)
            {
                _threadPoolTimer = ThreadPoolTimer.CreateTimer((source) =>
                {
                    _processingFace  = false;
                    _threadPoolTimer = null;
                },
                                                               TimeSpan.FromMilliseconds(3500));
            }
        }
Example #22
0
        private async void Timer_Tick(ThreadPoolTimer timer)
        {
            Debug.WriteLine("TICK");
            await UpdateAllData();

            this.timer = ThreadPoolTimer.CreateTimer(Timer_Tick, TimeSpan.FromSeconds(10));
        }
Example #23
0
 // Resets the timer and starts over.
 public void ResetScreensaverTimeout()
 {
     _moveTimer?.Cancel();
     _timeoutTimer?.Cancel();
     _timeoutTimer        = ThreadPoolTimer.CreateTimer(TimeoutTimer_Tick, TimeSpan.FromMinutes(1));
     IsScreensaverVisible = false;
 }
Example #24
0
        private void PasteEffectInvoke(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            if (CheckedLayer == null || g_CanPaste == false || CopiedEffect == null)
            {
                return;
            }

            args.Handled = true;
            g_CanPaste   = false;

            var copy = new EffectLineViewModel(CopiedEffect);

            copy.Left = (CheckedEffect != null) ? CheckedEffect.Right : 0;

            if (!CheckedLayer.TryInsertToTimelineFitly(copy))
            {
                // TODO
                g_CanPaste = true;
                return;
            }

            TimeSpan        delay      = TimeSpan.FromMilliseconds(400);
            ThreadPoolTimer DelayTimer = ThreadPoolTimer.CreateTimer(
                (source) =>
            {
                Dispatcher.RunAsync(
                    CoreDispatcherPriority.High,
                    () =>
                {
                    g_CanPaste = true;
                });
            }, delay);
        }
Example #25
0
 public static void FireFontFamilyListChanged(UInt32 cbAttachment)
 {
     if (FontFamilyListChanged != null)
     {
         //폰트의 저장된 갯수(호출 횟수)와 매개변수의 갯수가 같으면 폰트 로드를 호출
         if (cbAttachment <= cntSaveFont)
         {
             DispatcherHelper.CheckBeginInvokeOnUI(() =>
             {
                 //이벤트 처리
                 if (isChanged)
                 {
                     FontFamilyListChanged(null, null);
                     isChanged = false;
                 }
             });
         }
         else
         {
             ThreadPoolTimer.CreateTimer(handler =>
             {
                 FireFontFamilyListChanged(cbAttachment);
             }, TimeSpan.FromMilliseconds(100));
         }
     }
 }
        private void CreateTimerMilliseconds(int milliseconds)
        {
            // Create timer
#if NETFX_CORE || WINDOWS_PHONE
            if (timer == null)
            {
                // Creates a single-use timer.
                // https://msdn.microsoft.com/en-US/library/windows/apps/windows.system.threading.threadpooltimer.aspx
                timer = ThreadPoolTimer.CreateTimer(
                    OnTimerElapsed,
                    TimeSpan.FromMilliseconds(milliseconds));
            }
#else
            if (timer == null)
            {
                // Generates an event after a set interval
                // https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
                timer          = new Timer(milliseconds);
                timer.Elapsed += OnTimerElapsed;
                // the Timer should raise the Elapsed event only once (false)
                timer.AutoReset = false;        // fire once
                timer.Enabled   = true;         // Start the timer
            }
#endif // NETFX_CORE
        }
Example #27
0
 private void MainCanvas_PointerMoved(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
 {
     if (isImmersiveMode)
     {
         if (isImmersiveAllIn)
         {
             Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);
             ImmersiveAllBack.Begin();
             isImmersiveAllIn = false;
         }
         if (Context.ImmersiveTimeout == 0)
         {
             if (immersiveTimer != null)
             {
                 immersiveTimer.Cancel();
             }
             return;
         }
         if (immersiveTimer != null)
         {
             immersiveTimer.Cancel();
         }
         immersiveTimer = ThreadPoolTimer.CreateTimer(async(task) =>
         {
             await GotoImmersiveAllin();
         }, TimeSpan.FromSeconds(Context.ImmersiveTimeout));
     }
 }
Example #28
0
 //开始行走
 private void StartWalk()
 {
     if (_pathPoint.Count == 0)
     {
         Debug.WriteLine("no path");
     }
     else
     {
         var x = _pathPoint.ElementAt(0).X.ToString(CultureInfo.CurrentCulture);
         var y = _pathPoint.ElementAt(0).Y.ToString(CultureInfo.CurrentCulture);
         InvokeJsStart(x, y);
         Debug.WriteLine("start run");
         InvokeJsHeading(0);
         var delay      = TimeSpan.FromSeconds(2);
         var delayTimer = ThreadPoolTimer.CreateTimer
                              (source =>
         {
             if (_pathPoint.Count > 1)
             {
                 TestClick(1, 1);
             }
             else
             {
                 TestClick(1, 1);
                 Debug.WriteLine("can't move");
             }
         }, delay);
     }
 }
Example #29
0
        internal void SetSleepTimer(DateTime t, SleepAction a)
        {
            sleepTimer?.Cancel();
            sleepTime   = t;
            sleepAction = a;
            var period = (t - DateTime.Now).Subtract(TimeSpan.FromSeconds(30));

            sleepTimer = ThreadPoolTimer.CreateTimer(async work =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
                {
                    PopMessage($"In {(sleepTime - DateTime.Now).TotalSeconds.ToString("0")} seconds sleep timer will activate");
                    await Task.Delay(Convert.ToInt32((sleepTime - DateTime.Now).TotalMilliseconds));
                    switch (sleepAction)
                    {
                    case SleepAction.Pause:
                        MainPageViewModel.Current.PlayPause.Execute();
                        break;

                    case SleepAction.Stop:
                        MainPageViewModel.Current.Stop.Execute();
                        break;

                    case SleepAction.Shutdown:
                        Application.Current.Exit();
                        break;

                    default:
                        break;
                    }
                });
            }, period.TotalSeconds < 0 ? TimeSpan.FromSeconds(1) : period, destroy =>
            {
            });
        }
Example #30
0
        internal static ITimer CreateTimer <TResponse>(this AsyncState <TResponse> state, TimeSpan timeOut)
        {
#if NETFX_CORE
            return(new NetFxAsyncTimer(ThreadPoolTimer.CreateTimer(request.TimedOut, timeOut)));
#else
            return(new AsyncTimer(new Timer(state.TimedOut, state, (int)timeOut.TotalMilliseconds, Timeout.Infinite)));
#endif
        }