void VisualElementsRequestedHandler(object sender, VisualElementsRequestedEventArgs args) { // Request the deferral object if additional time is needed to acquire or process the assets. // The Pin to Start Flyout will display a progress control during this time. VisualElementsRequestDeferral deferral = args.Request.GetDeferral(); // This delay is to simulate doing an async operation or any processing that will // take a noticeable amount of time to complete. ThreadPoolTimer.CreateTimer( async(timer) => { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.SetAlternativeElements(args); // Once the assets have been assigned, this signals the Pin to Start Flyout to show the tiles. // If the deferral does not complete before the fly out times out, the default assets provided // at the time when the request to pin the tile was made will be used. deferral.Complete(); }); }, TimeSpan.FromSeconds(3)); }
private async void VerifyDistractions(ThreadPoolTimer timer) { if (!IsInternet()) { await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { if ((ShowButton.GetCurrentState() == ClockState.Stopped || ShowButton.GetCurrentState() == ClockState.Filling) && BtNext.Visibility != Visibility.Visible) { ShowButton.Begin(); } }); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { if ((HideButton.GetCurrentState() == ClockState.Stopped || HideButton.GetCurrentState() == ClockState.Filling) && BtNext.Visibility != Visibility.Collapsed) { HideButton.Begin(); } }); } }
/// <summary> /// Starts clicking at current click interval. The interval will not change unless restarted. /// </summary> public void Start() { if (IsRunning) { timer.Cancel(); } timer = ThreadPoolTimer.CreatePeriodicTimer((source) => { injector = InputInjector.TryCreate(); injector.InjectMouseInput(new InjectedInputMouseInfo[] { new InjectedInputMouseInfo { MouseOptions = InjectedInputMouseOptions.LeftDown }, new InjectedInputMouseInfo { MouseOptions = InjectedInputMouseOptions.LeftUp }, }); }, TimeSpan.FromMilliseconds(ClickInterval)); IsRunning = true; }
// Should be called right after the constructor (since constructors can't have async calls) public async Task InitializeAsync() { logFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("logs.txt", CreationCollisionOption.OpenIfExists); // We don't want to write to disk every single time a log event occurs, so let's schedule a // thread pool task periodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) => { // We have to lock when writing to disk as well, otherwise the in memory cache could change // or we might try to write lines to disk more than once lock (syncObj) { if (logLines.Count > 0) { // Write synchronously here. We'll never be called on a UI thread and you // cannot make an async call within a lock statement FileIO.AppendLinesAsync(logFile, logLines).AsTask().Wait(); logLines = new List <string>(); } } CheckLogFile(); }, TimeSpan.FromSeconds(5)); }
private async void Timer_Tick(ThreadPoolTimer t) { using (var db = new AppDbContext()) { var readings = db.Readings .Where(r => !r.Synchronized) .OrderBy(r => r.Date) .Take(150) .ToList(); var content = new StringContent(JsonConvert.SerializeObject(readings), Encoding.UTF8, "application/json"); var result = await _client.PostAsync("", content); if (result.IsSuccessStatusCode) { readings.ForEach(r => r.Synchronized = true); lock (AppDbContext.LockObject) { db.SaveChanges(); } } } }
private void Timer_Tick3(ThreadPoolTimer timer) { /* * iteration++; * if (iteration % 3 == 0) * { * currentPulseLength = ClockwisePulseLength; * secondPulseLength = CounterClockwisePulseLegnth; * } * else if (iteration % 3 == 1) * { * currentPulseLength = CounterClockwisePulseLegnth; * secondPulseLength = ClockwisePulseLength; * } * else * { * currentPulseLength = 0; * secondPulseLength = 0; * } */ //double desiredPercentage = currentPulseLength / (1000.0 / pwmController.ActualFrequency); //motorPin.SetActiveDutyCyclePercentage(desiredPercentage); }
//Production private Uri baseUri = new Uri("http://wssccatiot.westus.cloudapp.azure.com:8080/topic"); public MainPage() { ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen; this.InitializeComponent(); //Create timeer based ThreadPool task to get data from sensors and update UI ThreadPoolTimer readerTimer = ThreadPoolTimer.CreatePeriodicTimer(async (source) => { await ClearScreen(); var item = await GetGraphData(); if (item != null) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => items.Add(item)); await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => UpdateScreen()); } await PostDataAsync(); }, TimeSpan.FromSeconds(3)); }
private void DelayGetPath() { var delay = TimeSpan.FromSeconds(2); var delayTimer = ThreadPoolTimer.CreateTimer (async source => { await Dispatcher.RunAsync( CoreDispatcherPriority.High, async() => { var result = await Webview1.InvokeScriptAsync("eval", new[] { "getNetCheck()" }); Debug.WriteLine(result); if (result.Equals("Y")) { InvokeJsGetPath(); //得出路径 } else { Debug.WriteLine("network wrong!"); } }); }, delay); }
public void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); //Motor starts off currentPulseWidth = 0; //The stopwatch will be used to precisely time calls to pulse the motor. stopwatch = Stopwatch.StartNew(); GpioController controller = GpioController.GetDefault(); servoPin = controller.OpenPin(13); servoPin.SetDriveMode(GpioPinDriveMode.Output); timer = ThreadPoolTimer.CreatePeriodicTimer(this.Tick, TimeSpan.FromSeconds(2)); //You do not need to await this, as your goal is to have this run for the lifetime of the application Windows.System.Threading.ThreadPool.RunAsync(this.MotorThread, Windows.System.Threading.WorkItemPriority.High); }
public 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 // // Do not close application after startup _backgroundTaskDeferral = taskInstance.GetDeferral(); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceName, deviceKey));//commented due to: CS0104 C# is an ambiguous reference, TransportType.Http1 // Execute first run GetSensorReadings(); // Set task to be run in background ThreadPoolTimer.CreatePeriodicTimer(timer => { GetSensorReadings(); }, new TimeSpan(0, 0, settings.timerCheckIntervall)); }
private void SampleTimerCallback(ThreadPoolTimer timer) { if ((_cancelRequested == false) && (_taskInstance.Progress < 100)) { _taskInstance.Progress += 10; Message = $"Background Task {_taskInstance.Task.Name} running"; } else { timer.Cancel(); if (_cancelRequested) { Message = $"Background Task {_taskInstance.Task.Name} cancelled"; } else { Message = $"Background Task {_taskInstance.Task.Name} finished"; } _deferral?.Complete(); } }
public MainPage() { this.InitializeComponent(); UpdateTime(); UpdateWeather(); _clockTimer = ThreadPoolTimer.CreatePeriodicTimer((source) => { Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { UpdateTime(); }); }, TimeSpan.FromMilliseconds(1000)); _weatherTimer = ThreadPoolTimer.CreatePeriodicTimer((source) => { Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { UpdateWeather(); }); }, TimeSpan.FromHours(1)); }
public async void ShowNewTicket(string ticketCode, string barberName) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { if (ticketCode != string.Empty) { NextClientMessage.Text = string.Format("Cliente {0} pase", ticketCode); NextClientMessage3.Text = string.Format(barberName); NextClientDialog.ShowAsync(); } await GetActiveBarbers(); ThreadPoolTimer hideContentTimer = ThreadPoolTimer.CreateTimer( async(timer) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { NextClientDialog.Hide(); }); }, TimeSpan.FromSeconds(10)); }); }
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously public IAsyncAction WriteMessageAsync(string message, uint timeout) { return(Task.Run(async() => { if (timeout == 0) { currentMessage = message; await this.WriteMessageInternal(currentMessage); } else { if (tempTimer != null) { tempTimer.Cancel(); tempTimer = null; } tempMessage = message; tempTimer = ThreadPoolTimer.CreateTimer(Timer_Tick, new TimeSpan(0, 0, (int)timeout)); await this.WriteMessageInternal(tempMessage); } }).AsAsyncAction()); }
// // Simulate the background task activity. // private void PeriodicTimerCallback(ThreadPoolTimer timer) { if ((_cancelRequested == false) && (_progress < 100)) { _progress += 10; _taskInstance.Progress = _progress; } else { _periodicTimer.Cancel(); // // Record that this background task ran. // String taskStatus = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed"; Debug.WriteLine("Background " + _taskInstance.Task.Name + taskStatus); // // Indicate that the background task has completed. // _deferral.Complete(); } }
private async Task InitializeMediaCapture() { try { this.mediaCapture = new MediaCapture(); // For this scenario, we only need Video (not microphone) so specify this in the initializer. // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail. MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings(); settings.StreamingCaptureMode = StreamingCaptureMode.Video; await this.mediaCapture.InitializeAsync(settings); //this.mediaCapture.CameraStreamStateChanged += this.MediaCapture_CameraStreamStateChanged; // Cache the media properties as we'll need them later. var deviceController = this.mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // Immediately start streaming to our CaptureElement UI. // NOTE: CaptureElement's Source must be set before streaming is started. this.captureElement.Source = this.mediaCapture; await this.mediaCapture.StartPreviewAsync(); this.isPreviewStreaming = true; // Use a 66 milisecond interval for our timer, i.e. 15 frames per second TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval); } catch (System.UnauthorizedAccessException) { } catch (Exception ex) { } }
public MainPage() { this.InitializeComponent(); Debug.WriteLine("Hello"); ViewModel.Rule = rule; ViewModel.CurrentStatus = lastProfile; NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; var profiles = NetworkInformation.GetConnectionProfiles(); PrintStatus(profiles); var p = NetworkInformation.GetInternetConnectionProfile(); NotifyCurrentStatus(p); this.ViewModel.CurrentStatus = p; var PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source) => { var temp_last = this.ViewModel.CurrentStatus; var temp_current = NetworkInformation.GetInternetConnectionProfile(); await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { this.ViewModel.CurrentStatus = temp_current; if (!temp_last.IsSameCondition(temp_current, rule)) { NotifyCurrentStatus(temp_current); } }); }, TimeSpan.FromSeconds(3)); }
/// <summary> /// Should be called externally to listen on key /// down events. /// /// Caution: /// - It only listens on Gamepad keys. /// </summary> /// <param name="args"></param> public void OnKeyDown(KeyEventArgs args) { // Ensure that controller selection mode is // selected and no cool down is active. if (isKeyDownCooldownActive || selectedMode != HomeBearTiltControlMode.XBOX_CONTROLLER) { return; } // Listen on pressed keys. // Use only GamePad ones and trigger actions. switch (args.VirtualKey) { // Stick upwards. case VirtualKey.GamepadLeftThumbstickUp: PositiveTiltCommand.Execute(null); break; // Stick downwards. case VirtualKey.GamepadLeftThumbstickDown: NegativeTiltCommand.Execute(null); break; // Stick to the left. case VirtualKey.GamepadLeftThumbstickLeft: PositivePanCommand.Execute(null); break; // Stick to the right. case VirtualKey.GamepadLeftThumbstickRight: NegativePanCommand.Execute(null); break; } // Start cool down timer. keyDownCooldownTimer = ThreadPoolTimer.CreateTimer(CooldownTimer_Tick, KEYDOWN_COOLDOWN_SECONDS); }
public async void Run(IBackgroundTaskInstance taskInstance) { // Ensure our background task remains running taskDeferral = taskInstance.GetDeferral(); // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage mutex = new Mutex(false, mutexId); // Initialize WeatherShield await shield.BeginAsync(); //Initialise the MCP3008 ADC Chip mcp3008.Initialize(); //Initialise an attached web cam ready to take an image await webcam.InitialiseCamerAsync(); // Create a timer-initiated ThreadPool task to read data from I2C i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds)); //Create a timer-initiated ThreadPool task to read data from the interrupt handler counting the wind instrument activity windInterruptSample = ThreadPoolTimer.CreatePeriodicTimer(MeasureWindEventData, TimeSpan.FromSeconds(windInterruptSampleInterval)); //Create a timer driven thread pool task to take a photo. pictureTimer = ThreadPoolTimer.CreatePeriodicTimer(TakePhoto, TimeSpan.FromSeconds(pictureTimerSeconds)); // Task cancellation handler, release our deferral there taskInstance.Canceled += OnCanceled; //Create the interrupt handler listening to the wind speed pin (13). Triggers the GpioPin.ValueChanged event on that pin //connected to the anemometer. shield.WindSpeedPin.ValueChanged += WindSpeedPin_ValueChanged; //Create the interrupt handler listening to the rain guage pin (26). Triggers the Gpio.ValueChanged event on that pin //connected to the rain guage. shield.RainPin.ValueChanged += RainPin_ValueChanged; }
public SimulatedGpioPin(int gpioNumber, GpioPinDriveMode driveMode, bool setInitialValueHigh = false, SimulatedVehicleCommunication communicaton = null, int interruptInterval = 0) { try { PinNumber = gpioNumber; _pinMode = driveMode; if (gpioNumber < 0) { throw new Exception("Pin number is out of range"); } _isInputPin = driveMode == GpioPinDriveMode.Input || driveMode == GpioPinDriveMode.InputPullUp || driveMode == GpioPinDriveMode.InputPullDown; if (_isInputPin) { if (communicaton != null) { communicaton.NewDataReceived += OnNewDataReceivedFromSensor; } _interruptTimer = StartInterruptTimer(interruptInterval); _pinHigh = true; } else { PinHigh = setInitialValueHigh; } ErrorWhenOpeningPin = false; } catch (Exception e) { ErrorWhenOpeningPin = true; _exceptionWhenOpeningPin = e; } }
private void Timer_Tick(ThreadPoolTimer timer) { timer.Cancel(); list.Clear(); var sw = new Stopwatch(); sw.Start(); var mercury = new MercuryAccess(); var success = mercury.CallMPS().Result; sw.Stop(); elapsedTime = (double)sw.ElapsedMilliseconds / (double)1000.0; list.Add(string.Format("{0} ElapsedTime: {1}", DateTime.Now, elapsedTime)); totalTime += elapsedTime; list.Add(string.Format("{0} TotalTime: {1}", DateTime.Now, totalTime)); totalTransactions++; list.Add(string.Format("{0} Total Transactions: {1}", DateTime.Now, totalTransactions)); averageTimePerTransaction = (double)totalTime / (double)totalTransactions; list.Add(string.Format("{0} Average Transaction Time: {1}", DateTime.Now, averageTimePerTransaction)); totalToBlinkGreen = 10; totalToBlinkRed = 10; NextActionIsShowTransactionTiming = true; ShowTransactionSuccess(success); }
private async Task <bool> StartWebcamStreamingAsync() { _faceTracker = await FaceTracker.CreateAsync(); try { _mediaCapture = new MediaCapture(); await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Video }); _mediaCapture.Failed += (s, a) => AbandonStreaming(); var deviceController = _mediaCapture.VideoDeviceController; _videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; CameraPreview.Source = _mediaCapture; await _mediaCapture.StartPreviewAsync(); var timerInterval = TimeSpan.FromMilliseconds(66); // 66ms, aprox 15 fps _frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(ProcessCurrentVideoFrame, timerInterval); return(true); } catch (UnauthorizedAccessException) { NavigateToPermissionsPage(); return(false); } catch (Exception exception) { await DisplayMessage($"Error al iniciar el stream de la cámara: {exception.Message}"); return(false); } }
private async Task subscribe(NetWorkSubscriberPayload payload) { if (string.IsNullOrEmpty(netWorkSocketListener.Hostname)) { return; } try { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("SUBSCRIBE"), new Uri(payload.URI)); request.Headers.Add("User-Agent", "RaumfeldControl/0.0 RaumfeldProtocol/1"); /* RaumfeldControl/3.6 RaumfeldProtocol/399 Build => https://github.com/masmu/pulseaudio-dlna/issues/227 */ request.Headers.Add("Accept-Language", "en"); request.Headers.Add("ContentType", "text/xml; charset=\"utf - 8\""); request.Headers.Add("CALLBACK", "<" + netWorkSocketListener.Hostname + ">"); request.Headers.Add("NT", "upnp:event"); request.Headers.Add("TIMEOUT", "Second-300"); HttpResponseMessage response = await httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { SubscriberDictionary[payload] = response.Headers["SID"]; if (Timer == null) { Timer = ThreadPoolTimer.CreatePeriodicTimer(async(t) => { await updateSubscribe(); }, TimeSpan.FromSeconds(240)); } } else { await messagingService.ShowErrorDialogAsync(string.Format("{0}: {1}", response.StatusCode, await response.Content.ReadAsStringAsync())); } } catch (Exception) { } }
int pixelCounter; // zero-based 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(); // set the security for fms ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // hook into FMS from settings in the config file fmserver = GetFMSinstance(); token = string.Empty; // hook into the sense hat senseHat = await SenseHatFactory.GetSenseHat(); // clear the LEDs senseHat.Display.Clear(); senseHat.Display.Update(); pixelCounter = 0; // log into the Events Tracing for Windows ETW // on the Device Portal, ETW tab, pick "Microsoft-Windows-Diagnostics-LoggingChannel" from the registered providers // pick level 5 and enable lc = new LoggingChannel("SenseHatFms", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a")); lc.LogMessage("Starting up."); // start the timer ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromSeconds(2)); }
public LM7SegDirect(byte segA, byte segB, byte segC, byte segD, byte segE, byte segF, byte segG, byte segDotn, bool isAnode) { byte[] pin_order = new byte[8]; _isAnode = isAnode; pin_order[0] = segA; pin_order[1] = segB; pin_order[2] = segC; pin_order[3] = segD; pin_order[4] = segE; pin_order[5] = segF; pin_order[6] = segG; pin_order[7] = segDotn; gpio = GpioController.GetDefault(); // Show an error if there is no GPIO controller if (gpio == null) { //@@ } //---------------- // Open each pin and turn the light of for it for (int i = 0; i < 8; i++) { pins[i] = gpio.OpenPin(pin_order[i]); pins[i].Write(GpioPinValue.High); pins[i].SetDriveMode(GpioPinDriveMode.Output); } //---------- // Create a timer that redraw the currentvalue each second // OBS: If you want to change numbers faster than that, just fix the timespan for this timer timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(1)); }
//嵌入朝向 private void InvokeJsHeading(int tmpNodeNum) { Debug.WriteLine("insert label"); var delay = TimeSpan.FromSeconds(2); var delayTimer = ThreadPoolTimer.CreateTimer (async source => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { string[] insertMessage = { "insertMark(" + _pathPoint[tmpNodeNum].X + "," + _pathPoint[tmpNodeNum].Y + "," + tmpNodeNum + ")" }; var result = await Webview1.InvokeScriptAsync("eval", insertMessage); /*string[] args = {"setMarkHeading()"}; * result = await Webview1.InvokeScriptAsync("eval", args); //镜头转换,待改善 * Debug.WriteLine("result" + result);*/ }); }, delay); }
private async void TimerElapsedHandler(ThreadPoolTimer timer) { if (writer != null) { writer.WriteByte(0xFF); writer.WriteByte(length); writer.WriteByte(angle); await writer.StoreAsync(); //Debug.WriteLine("{0} ; {1}", length, angle); debounceCounter--; if (debounceCounter <= 0) { debounceCounter = 0; leftSliderValue = 0; rightSliderValue = 0; length = 0; angle = 0; } } }
private async void AdaptersEnumCompleted(DeviceWatcher sender, object args) { Log.Enter(); List <String> WiFiAdaptersID = new List <string>(WiFiAdapters.Keys); for (int i = 0; i < WiFiAdaptersID.Count; i++) { string id = WiFiAdaptersID[i]; try { WiFiAdapters[id] = await WiFiAdapter.FromIdAsync(id); } catch (Exception) { WiFiAdapters.Remove(id); } } EnumAdaptersCompleted.Set(); if (WiFiAdapters.Count() > 0) { wifiRefreshTimer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, refreshTimespan); } Log.Leave(); }
private async void UpdateTimeAndDate(ThreadPoolTimer timer) { var now = DateTime.Now; string time = now.ToString("hh:mm tt"); if (time.StartsWith("0")) { time = time.Substring(1); } CurrentTime = time; // Standard long date format using the current system language CurrentDate = now.Date.ToString("D"); // Check to see if enough time has passed since the last reading in order to send a new message TimeSpan diff = now.Subtract(_latestMessageTimestamp); if (diff.TotalMinutes >= MessageTimeLimit) { // Upload Temperature and Humidity readings to the Azure IoT Hub, if configured _latestMessageTimestamp = now; await _sensorServer.SendSensorDataToAzureAsync(); if (Settings.MapFlipEnabled) { FlipDisplay(); } } // Rough estimates for sunrise and sunset var sunset = DateTime.Parse("8:00 PM"); var sunrise = DateTime.Parse("5:00 AM"); ColorScheme = (now > sunrise && now < sunset) ? MapColorScheme.Light : MapColorScheme.Dark; }
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) { UpdateRequested?.Invoke(this, EventArgs.Empty); // 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( e => { UpdateRequested?.Invoke(this, EventArgs.Empty); if (TimeSampleEditedFirst == DateTime.MinValue) { TimeSampleEditedFirst = DateTime.Now; } TimeSampleEditedLast = DateTime.Now; }, TimeSpan.FromSeconds(0.5)); } }
public NinjectTimer2(NinjectTimerCallback callback, long interval) { this.timer = ThreadPoolTimer.CreatePeriodicTimer(t => callback(), TimeSpan.FromMilliseconds(interval)); }
void OnTimer(ThreadPoolTimer t) { this.callback(this.state); }
public Timer(TimerCallback callback, object state, int dueTime, int period) { this.callback = callback; this.state = state; this.timer = ThreadPoolTimer.CreatePeriodicTimer(this.OnTimer, TimeSpan.FromMilliseconds(dueTime)); }