public async Task Restart_DifferentCallback() { // Verify that we can restart a timer using the original interval // and a different callback. var ticks0 = 0; var ticks1 = 0; using (var timer = new AsyncTimer( async() => { ticks0++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.False(timer.IsRunning); Assert.Equal(0, ticks0); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks0 == 5); timer.Stop(); ticks0 = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks0 == 0); timer.Start( callback: async() => { ticks1++; await Task.CompletedTask; }); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks1 == 5); timer.Stop(); ticks1 = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks1 == 0); } }
public async Task It_continues_to_run_after_an_error() { var callbackInvokedAfterError = new TaskCompletionSource <bool>(); var fail = true; var exceptionThrown = false; var timer = new AsyncTimer(); timer.Start((time, token) => { if (fail) { fail = false; throw new Exception("Simulated!"); } Assert.IsTrue(exceptionThrown); callbackInvokedAfterError.SetResult(true); return(Task.FromResult(0)); }, TimeSpan.Zero, e => { exceptionThrown = true; }, Task.Delay); Assert.IsTrue(await callbackInvokedAfterError.Task.ConfigureAwait(false)); }
public async Task Stop_cancels_token_while_waiting() { var timer = new AsyncTimer(); var waitCancelled = false; var delayStarted = new TaskCompletionSource <bool>(); timer.Start((time, token) => { throw new Exception("Simulated!"); }, TimeSpan.FromDays(7), e => { //noop }, async(delayTime, token) => { delayStarted.SetResult(true); try { await Task.Delay(delayTime, token).ConfigureAwait(false); } catch (OperationCanceledException) { waitCancelled = true; } }); await delayStarted.Task.ConfigureAwait(false); await timer.Stop().ConfigureAwait(false); Assert.IsTrue(waitCancelled); }
public async Task Stop_cancels_token_while_in_callback() { var timer = new AsyncTimer(); var callbackCancelled = false; var callbackStarted = new TaskCompletionSource <bool>(); var stopInitiated = new TaskCompletionSource <bool>(); timer.Start(async(time, token) => { callbackStarted.SetResult(true); await stopInitiated.Task.ConfigureAwait(false); if (token.IsCancellationRequested) { callbackCancelled = true; } }, TimeSpan.Zero, e => { //noop }, Task.Delay); await callbackStarted.Task.ConfigureAwait(false); var stopTask = timer.Stop(); stopInitiated.SetResult(true); await stopTask.ConfigureAwait(false); Assert.IsTrue(callbackCancelled); }
public async Task Stop_waits_for_callback_to_complete() { var timer = new AsyncTimer(); var callbackCompleted = new TaskCompletionSource <bool>(); var callbackTaskStarted = new TaskCompletionSource <bool>(); timer.Start((time, token) => { callbackTaskStarted.SetResult(true); return(callbackCompleted.Task); }, TimeSpan.Zero, e => { //noop }, Task.Delay); await callbackTaskStarted.Task.ConfigureAwait(false); var stopTask = timer.Stop(); var delayTask = Task.Delay(1000); var firstToComplete = await Task.WhenAny(stopTask, delayTask).ConfigureAwait(false); Assert.AreEqual(delayTask, firstToComplete); callbackCompleted.SetResult(true); await stopTask.ConfigureAwait(false); }
public async Task It_continues_to_run_after_an_error() { var callbackInvokedAfterError = new TaskCompletionSource <bool>(); var fail = true; var exceptionThrown = false; var timer = new AsyncTimer(); timer.Start( callback: (_, _) => { if (fail) { fail = false; throw new Exception("Simulated!"); } Assert.True(exceptionThrown); callbackInvokedAfterError.SetResult(true); return(Task.FromResult(0)); }, interval: TimeSpan.Zero, errorCallback: _ => { exceptionThrown = true; }, delayStrategy: Task.Delay); Assert.True(await callbackInvokedAfterError.Task); }
public void Start() { if (paused) { paused = false; } else { _tcpServer = new TcpServer { Port = _config.DevServer_TcpPort, ReceiveTimeout = _config.TcpResponseTimeout / 2, SendTimeout = _config.TcpResponseTimeout / 2, ThreadName = "DevServer_ESP_TCP", }; _tcpServer.GotNewClient += GotNewClient; _tcpServer.Start(); DateTimeService.Instance.HourChanged += OnHourChanged; _scanTimer = new AsyncTimer(_config.DeviceScanTime); _scanTimer.CallBack += Scan_CallBack; _scanTimer.Start(); } }
public async Task Dispose() { // Verify that [Dispose()] stops the timer. var ticks = 0; var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; }); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); timer.Dispose(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); // Verify that calling [Dispose()] on an already disposed timer // does not throw an exception. timer.Dispose(); }
public async Task Stop_cancels_token_while_in_callback() { var timer = new AsyncTimer(); var callbackCanceled = false; var callbackStarted = new TaskCompletionSource <bool>(); var stopInitiated = new TaskCompletionSource <bool>(); timer.Start( callback: async(_, token) => { callbackStarted.SetResult(true); await stopInitiated.Task; if (token.IsCancellationRequested) { callbackCanceled = true; } }, interval: TimeSpan.Zero, errorCallback: _ => { //noop }, delayStrategy: Task.Delay); await callbackStarted.Task; var stopTask = timer.Stop(); stopInitiated.SetResult(true); await stopTask; Assert.True(callbackCanceled); }
public async Task StartStop_DelayFirstTick() { var ticks = 0; // Verify that basic start/stop operations work when // delaying the first tick callback. using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1), delayFirstTick: true); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 4); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
public async Task Stop_waits_for_callback_to_complete() { var timer = new AsyncTimer(); var callbackCompleted = new TaskCompletionSource <bool>(); var callbackTaskStarted = new TaskCompletionSource <bool>(); timer.Start( callback: (_, _) => { callbackTaskStarted.SetResult(true); return(callbackCompleted.Task); }, interval: TimeSpan.Zero, errorCallback: _ => { //noop }, delayStrategy: Task.Delay); await callbackTaskStarted.Task; var stopTask = timer.Stop(); var delayTask = Task.Delay(1000); var firstToComplete = await Task.WhenAny(stopTask, delayTask); Assert.Equal(delayTask, firstToComplete); callbackCompleted.SetResult(true); await stopTask; }
public async Task StartStop() { // Verify that basic start/stop operations work. var ticks = 0; using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.Equal(TimeSpan.Zero, timer.Interval); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); Assert.Equal(TimeSpan.FromSeconds(1), timer.Interval); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
static void Main() { AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); }
public async Task WaitAsync(double seconds) { AsyncTimer timer = new AsyncTimer(TimeSpan.FromSeconds(seconds)); timer.Start(); await Task.WhenAny(timer.CompletionSource.Task); await Context.Channel.SendMessageAsync($"The timer has timed out. ({Format.Counter(timer.ElapsedTime.TotalSeconds)})"); }
static void Main() { AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); }
public static void Main() { AsyncTimer timerOne = new AsyncTimer(PrintText, 7, 2000); timerOne.Start(); AsyncTimer timerTwo = new AsyncTimer(PrintNumbers, 10, 1000); timerTwo.Start(); }
public void Errors() { // Check error detection. var timer = new AsyncTimer(async() => await Task.CompletedTask); Assert.Throws <ArgumentException>(() => timer.Start(TimeSpan.FromSeconds(-1))); Assert.Throws <InvalidOperationException>(() => timer.Start()); timer.Dispose(); Assert.Throws <ObjectDisposedException>(() => timer.Start(TimeSpan.FromSeconds(1))); Assert.Throws <ObjectDisposedException>(() => timer.Stop()); timer = new AsyncTimer(); Assert.Throws <InvalidOperationException>(() => timer.Start(TimeSpan.FromSeconds(1))); timer.Dispose(); }
public async Task Restart_DifferentInterval() { // Verify that we can restart a timer using a different interval // and also delaying the first tick. var ticks = 0; using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); timer.Start(TimeSpan.FromSeconds(2), delayFirstTick: true); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 2); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
public async Task Restart_SameInterval() { // Verify that we can restart a timer using the original interval. var ticks = 0; using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); timer.Start(); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
public async Task Start(Action <Blueprint> onChanged, Action <Exception> onError) { await Refresh(onChanged).ConfigureAwait(false); if (updateInterval == TimeSpan.Zero) { return; } updateTimer.Start(() => Refresh(onChanged), updateInterval, ex => { onError(ex); }); }
public async Task AsyncTimer_Invokes_Action_On_Start() { int count = 0; var timer = new AsyncTimer(() => { count += 1; return(Task.CompletedTask); }, Timeout.InfiniteTimeSpan, default(CancellationToken)); timer.Start(); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.Equal(1, count); }
static void Main() { AsyncTimer aTimer = new AsyncTimer(asyncMethod, 1000, 50); aTimer.Start(); //the code below is for testing asynchronous execution of method: int count = 1000; while (count >= 0) { Thread.Sleep(200); count--; Console.WriteLine(count); } }
public static void Main() { Action <string> method = delegate(string str) { Console.WriteLine(str); Console.Beep(); }; Action <string> method2 = str => Console.WriteLine("Hurry up!");; AsyncTimer timer = new AsyncTimer(method, 100, 1000); AsyncTimer timer2 = new AsyncTimer(method2, 100, 1000); timer.Start(); timer2.Start(); }
public async Task It_calls_error_callback() { var errorCallbackInvoked = new TaskCompletionSource <bool>(); var timer = new AsyncTimer(); timer.Start((time, token) => { throw new Exception("Simulated!"); }, TimeSpan.Zero, e => { errorCallbackInvoked.SetResult(true); }, Task.Delay); Assert.IsTrue(await errorCallbackInvoked.Task.ConfigureAwait(false)); }
public static void Main() { Action<string> method = delegate(string str) { Console.WriteLine(str); Console.Beep(); }; Action<string> method2 = str => Console.WriteLine("Hurry up!"); ; AsyncTimer timer = new AsyncTimer(method, 100, 1000); AsyncTimer timer2 = new AsyncTimer(method2, 100, 1000); timer.Start(); timer2.Start(); }
static void Main(string[] args) { var interestCalculator = new InterestCalculator(500m, 5.6m, 10, GetCompoundInterest); Console.WriteLine(interestCalculator); var compoundInterest = new InterestCalculator(2500m, 7.2m, 15, GetSimpleInterest); Console.WriteLine(compoundInterest); ////////////////// Async Timer //////////////////// AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); }
public void StartMovement(Vector2 direction) { lock (m_lock) { m_movementType = MovementType.Moving; m_direction = direction; m_lastMovementUpdate = Environment.TickCount; if (m_movementTimer.IsRunning) { m_movementTimer.Change(0, 1000, false); } else { m_movementTimer.Start(0, 1000, false); } } }
private async void CopyFilesAsyncButton_Click(object sender, EventArgs e) { if (CopyFilesAsyncButton.Text.Equals(copyFilesAsyncText)) { string sourceDirectory = @"C:\Users\barry\Source\Repos\CSharp-7-and-DotNET-Core-Cookbook-master\Chapter6\AsyncSource"; string destinationDirectory = @"C:\Users\barry\Source\Repos\CSharp-7-and-DotNET-Core-Cookbook-master\Chapter6\AsyncDestination"; CopyFilesAsyncButton.Text = cancelAsyncCopyText; cancellationTokenSource = new CancellationTokenSource(); elapsedTime = 0; AsyncTimer.Start(); IEnumerable <string> fileEntries = Directory.EnumerateFiles(sourceDirectory); foreach (string sourceFile in fileEntries) { using (FileStream sourceFileStream = File.Open(sourceFile, FileMode.Open)) { string destinationFilePath = $"{destinationDirectory}{Path.GetFileName(sourceFile)}"; using (FileStream destinationFileStream = File.Create(destinationFilePath)) { try { await sourceFileStream.CopyToAsync(destinationFileStream, 81920, cancellationTokenSource.Token); } catch (OperationCanceledException) { AsyncTimer.Stop(); TimerLabel.Text = $"Cancelled after {elapsedTime} seconds"; } } } } } if (!cancellationTokenSource.IsCancellationRequested) { AsyncTimer.Stop(); TimerLabel.Text = $"Completed in {elapsedTime} seconds"; } if (CopyFilesAsyncButton.Text.Equals(cancelAsyncCopyText)) { CopyFilesAsyncButton.Text = copyFilesAsyncText; Debug.Assert(cancellationTokenSource != null); cancellationTokenSource.Cancel(); } }
public async Task InitAsync() { // restart any builds that didn't finish before the last shutdown foreach (Build build in await _buildRepo.GetAllAsync()) { Engine engine = await _engineRepo.GetAsync(build.EngineId); if (engine != null) { EngineRunner runner = CreateRunner(engine.Id); await runner.RestartUnfinishedBuildAsync(build, engine); } else { // orphaned build, so delete it await _buildRepo.DeleteAsync(build); } } _commitTimer.Start(_options.Value.EngineCommitFrequency); }
static void Main() { // Chast ot resheniqta na problemite tuk sa vzeti ot foruma /* Solution for Problem 1/Interest Calculator/ */ var interest = new InterestCalculator(500m, 5.6m, 10, GetCompoundInterest); Console.WriteLine(interest); var compoundInterest = new InterestCalculator(2500m, 7.2m, 15, GetSimpleInterest); Console.WriteLine(compoundInterest); /* Solution for Problem 2/Async Timer/ */ AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); /* Solution for Problem 3/Student Class/ */ var student = new Student("Go6o", 17); student.Name = "Zara"; student.Age = 69; }
public async Task Callback_Exceptions() { // Verify that the timer continues to tick even when the callback // throws exceptions. var ticks = 0; using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; throw new Exception(); })) { timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); } }
private async Task InitializePrivate(List <TVideoHistory> views) { Histories = views; // 12分毎にリロードするタイマーを設定 Timer = new AsyncTimer(); Timer.Interval = TimeSpan.FromMinutes(12); Timer.Tick += async(sender, e) => { // 履歴に削除されたデータがないか確認 await RefreshAsync(); // 処理完了 Timer.Completed(); }; Timer.Start(); // 履歴に削除されたデータがないか確認 //await RefreshAsync(); await Task.Delay(1); }
private void InitializePrivate(IEnumerable <TFavorite> favorites) { foreach (var favorite in favorites) { Favorites.Add(favorite); } // 5分毎にリロードするタイマーを設定 Timer = new AsyncTimer(); Timer.Interval = TimeSpan.FromMinutes(5); Timer.Tick += async(sender, e) => { // マイリストに新着がないか確認 await Reload(); // 処理完了 Timer.Completed(); }; Timer.Start(); //// マイリストに新着がないか確認 //await Reload(); }
public virtual void Start() { var cleanupFailures = 0; timer.Start( callback: async(_, token) => { await cleanup(token); cleanupFailures = 0; }, interval: frequencyToRunCleanup, errorCallback: exception => { //TODO: log every exception cleanupFailures++; if (cleanupFailures >= 10) { criticalError(exception); cleanupFailures = 0; } }, delayStrategy: Task.Delay); }
public void StartTimer() { timer = new AsyncTimer(TimeSpan.FromMinutes(1), GetNewEpisode); timer.Start(); }
static void Main() { AsyncTimer timer = new AsyncTimer(writeSeconds, 500, 20); timer.Start(); }