/// <summary> /// Enqueues a push notification to be sent to the specified recipients in the background. /// </summary> /// <param name="notification">The message to send.</param> /// <param name="recipients">The recipients of the message.</param> /// <returns></returns> public void QueueSendNotification(PushNotification notification, List <PushSubscription> recipients) { var logger = _logger; _backgroundQueue.Enqueue(cancelToken => SendNotificationToRecipients( recipients.AsReadOnly(), notification, _emailOptions.SenderEmail, _appOptions.PushNotificationsPublicKey, _appOptions.PushNotificationsPrivateKey, logger, cancelToken)); }
public async Task DequeueAsync_Task_String() { // Arrange var token = new CancellationToken(); _taskQueue.Enqueue(t => Task.Run(() => Thread.Sleep(100), t)); // Act var result = await _taskQueue.DequeueAsync(token); await result(token); // Assert Assert.NotNull(result); }
public async Task StopAsync_GivenTask_ThenTaskCanceled() { var options = new BackgroundQueueOptions(); var queue = new BackgroundQueue(options); var tcs = new TaskCompletionSource <int>(); var delay = TimeSpan.FromMilliseconds(100); var stopwatch = Stopwatch.StartNew(); var delayTask = queue.Enqueue(async token => { tcs.SetResult(0); await Task.Delay(delay, token).ConfigureAwait(false); return(stopwatch.Elapsed); }); // make sure the delay task has started await tcs.Task.ConfigureAwait(false); var stopTask = queue.StopAsync(); await Assert.ThrowsAsync <TaskCanceledException>(async() => await Task.WhenAll(delayTask, stopTask).ConfigureAwait(false) ).ConfigureAwait(false); // the stop task should have ran to completion await stopTask.ConfigureAwait(false); }
private static void HandleExpiration <T>(HttpCacheShim that , CacheAddParameters <T> parameters , string cacheKey , CacheItemUpdateReason reason , out object expensiveObject , out CacheDependency dependency , out DateTime absoluteExpiration , out TimeSpan slidingExpiration) where T : class { Log("Expired", () => "(" + reason + ") " + cacheKey); expensiveObject = null; dependency = null; absoluteExpiration = Cache.NoAbsoluteExpiration; slidingExpiration = Cache.NoSlidingExpiration; // if we were not shutting down, might want to handle the reuse/refresh if (reason == CacheItemUpdateReason.Expired && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { if (parameters.ShouldScheduleRefresh && HttpCacheShim.DisableBackfill == false && !BackgroundQueue.IsBacklogged()) { // we need queue a request to the underlying store to get more current data into the cache so it stays primed. BackgroundQueue.Enqueue(parameters); } } }
public async Task ServiceShouldRunMaxConcurrentCountTaskWhenExistInQueue() { CancellationTokenSource tokenSource = new CancellationTokenSource(); BackgroundQueue queue = new BackgroundQueue((ex) => { throw ex; }, 10, 10);; BackgroundQueueService queueService = new BackgroundQueueService(queue); int highwaterMark = 0; for (int i = 0; i < 20; i++) { queue.Enqueue(async(ct) => { highwaterMark = Math.Max(queue.ConcurrentCount, highwaterMark); await Task.Delay(5); }); } var runningService = Task.Run(async() => await queueService.StartAsync(tokenSource.Token)); while (queue.Count > 0) { await Task.Delay(20); } highwaterMark.Should().BeGreaterThan(1); }
public async Task QueueTasksWhileRunning() { // Arrange var generated = new List <int>(); var expected = new List <int>(); for (var i = 0; i < 100; i++) { expected.Add(i); } // Act await HostedService.StartAsync(CancellationToken.None); for (var i = 0; i < 100; i++) { var count = i; BackgroundQueue.Enqueue(token => { generated.Add(count); return(Task.CompletedTask); }); } await Delay(1000, new CancellationTokenSource()); await HostedService.StopAsync(CancellationToken.None); // Assert all tasks are executed in correct order generated.Should().Equal(expected); }
public async Task ContinueRunningAfterFailedTask() { // Arrange var generated = new List <int>(); var expected = new List <int> { 1, 3 }; // Act await HostedService.StartAsync(CancellationToken.None); BackgroundQueue.Enqueue(token => { generated.Add(1); return(Task.CompletedTask); }); BackgroundQueue.Enqueue(token => throw new Exception("Other tasks should execute properly")); BackgroundQueue.Enqueue(token => { generated.Add(3); return(Task.CompletedTask); }); await Delay(1000, new CancellationTokenSource()); await HostedService.StopAsync(CancellationToken.None); // Assert tasks execute when another task fails generated.Should().Equal(expected); }
public IActionResult OnPost() { backgroundQueue.Enqueue(async(cancelToken) => { await LongRunningTask(); }); return(RedirectToAction("Index", "Home")); }
public async Task Enqueue_GivenStop_ThenDisposed() { var options = new BackgroundQueueOptions(); var queue = new BackgroundQueue(options); await queue.StopAsync().ConfigureAwait(false); await Assert.ThrowsAsync <InvalidOperationException>(async() => await queue.Enqueue(token => Task.FromResult(1)).ConfigureAwait(false) ).ConfigureAwait(false); }
public async Task Enqueue_GivenResult_ThenIsValid() { var options = new BackgroundQueueOptions(); var queue = new BackgroundQueue(options); var result = await queue.Enqueue(token => Task.FromResult(1)).ConfigureAwait(false); Assert.Equal(1, result); // cleanup await queue.StopAsync().ConfigureAwait(false); }
public async Task StartStop_Token_Void() { // Arrange var token = new CancellationToken(); _queue.Enqueue(t => Task.Run(() => Thread.Sleep(100), t)); // Act await _hostedService.StartAsync(token); await _hostedService.StopAsync(token); // Assert }
public async Task StopAsync_GivenCancelledToken_ThenTaskCanceled() { var options = new BackgroundQueueOptions(); var queue = new BackgroundQueue(options); var tcs = new TaskCompletionSource <int>(); var delay = queue.Enqueue(token => tcs.Task); var cancellationToken = new CancellationToken(true); await Assert.ThrowsAsync <TaskCanceledException>(async() => await queue.StopAsync(cancellationToken).ConfigureAwait(false) ).ConfigureAwait(false); tcs.SetResult(0); await delay.ConfigureAwait(false); }
private void AddAdminRepository_EventStoreHandler(object sender, AdminModel e) { try { // Record Add Command to Event Store backgroundQueue.Enqueue((cancellationToken) => this.eventStoreRepository?.SaveAsync(new EventModel() { TransactionId = TransactionId, EventName = "AddAdminCommand", OldData = null, NewData = JsonConvert.SerializeObject(e), CreatedDate = DateTime.Now.ToString() })); } finally { this.addAdminRepository.EventStoreHandler -= AddAdminRepository_EventStoreHandler; } }
private void MovieCreateRepository_DataEventStoreHandler(object sender, MovieModel newData) { // Run event using background task. backgroundQueue.Enqueue((cancellationToken) => { eventBus .RegisterEvent(new EventModel() { AggregateId = newData.AggregateId, StateId = newData.StateId, EventName = "MovieCreated", NewPayLoad = JsonConvert.SerializeObject(newData), CreatedDate = DateTime.Now }, new MovieCreatedEventHandler()) .BroadcastEventsAsync(); return(Task.CompletedTask); }); }
public async Task Enqueue_GivenDelay_ThenIsValid() { var options = new BackgroundQueueOptions(); var queue = new BackgroundQueue(options); var delay = TimeSpan.FromMilliseconds(100); var stopwatch = Stopwatch.StartNew(); var elapsed = await queue.Enqueue(async token => { await Task.Delay(delay, token).ConfigureAwait(false); return(stopwatch.Elapsed); }).ConfigureAwait(false); var delta = elapsed - delay; Assert.InRange(delta.TotalMilliseconds, 0, 25); // cleanup await queue.StopAsync().ConfigureAwait(false); }
public IActionResult SyncMpContactsToHubSpot() { using (_logger.BeginScope(AppEvent.Web.SyncMpContactsToHubSpot)) { try { var clickHereToViewProgress = $@"Click <a target=""blank"" href=""{Url.Action("ViewActivityState")}"">here</a> to view progress."; var activityProgress = _configurationService.GetCurrentActivityProgress(); if (activityProgress.ActivityState == ActivityState.Processing) { return(Content($"The HubSpot sync job is already processing. {clickHereToViewProgress}", "text/html")); } _backgroundQueue.Enqueue(async cancellationToken => await _syncService.Sync()); return(Content($"HubSpot sync job is now processing. {clickHereToViewProgress}", "text/html")); } catch (Exception exc) { _logger.LogError(AppEvent.Web.SyncMpContactsToHubSpot, exc, "An exception occurred while syncing MP contacts to HubSpot."); throw; } } }
private void MovieDeleteRepository_DataEventStoreHandler(object sender, Models.MovieModel deleteModel) { backgroundQueue?.Enqueue(async(cancellationToken) => { try { await eventBus ?.RegisterEvent(new EventModel() { AggregateId = deleteModel.AggregateId, StateId = deleteModel.StateId, EventName = "MovieDeleted", NewPayLoad = JsonConvert.SerializeObject(deleteModel), CreatedDate = DateTime.Now }, new MovieDeletedEventHandler()) ?.BroadcastEventsAsync(); } catch { throw; } }); }
private void MovieUpdateRepository_DataEventStoreHandler(object sender, MovieModel oldMovieModel, MovieModel newMovieModel) { backgroundQueue?.Enqueue(async(cancellationToken) => { await eventBus .RegisterEvent(new EventModel() { AggregateId = newMovieModel.AggregateId, StateId = newMovieModel.StateId, EventName = "MovieTitleChanged", NewPayLoad = JsonConvert.SerializeObject(newMovieModel), OldPayLoad = JsonConvert.SerializeObject(oldMovieModel), CreatedDate = DateTime.Now }, new MovieTitleChangedEventHandler()) .RegisterEvent(new EventModel() { AggregateId = newMovieModel.AggregateId, StateId = newMovieModel.StateId, EventName = "MovieReleaseDateChanged", NewPayLoad = JsonConvert.SerializeObject(newMovieModel), OldPayLoad = JsonConvert.SerializeObject(oldMovieModel), CreatedDate = DateTime.Now }, new MovieReleaseDateChangedEventHandler()) .RegisterEvent(new EventModel() { AggregateId = newMovieModel.AggregateId, StateId = newMovieModel.StateId, EventName = "MovieUpdate", NewPayLoad = JsonConvert.SerializeObject(newMovieModel), OldPayLoad = JsonConvert.SerializeObject(oldMovieModel), CreatedDate = DateTime.Now }, new MovieUpdatedEventHandler()) .BroadcastEventsAsync(); }); }
public async Task StopAsync_GivenShutdownTimeout_ThenTaskCanceled() { var options = new BackgroundQueueOptions { ShutdownTimeout = TimeSpan.FromMilliseconds(50) }; var queue = new BackgroundQueue(options); var tcs = new TaskCompletionSource <int>(); var delay = queue.Enqueue(token => tcs.Task); var stopwatch = Stopwatch.StartNew(); await Assert.ThrowsAsync <TaskCanceledException>(async() => await queue.StopAsync(CancellationToken.None).ConfigureAwait(false) ).ConfigureAwait(false); var elapsed = stopwatch.Elapsed; Assert.InRange(elapsed.TotalMilliseconds, 50, 100); tcs.SetResult(0); await delay.ConfigureAwait(false); }
public Task QueueRetryEmail(string emailId) { backgroundWorker.Enqueue(_ => RetryEmailWithTimeout(emailId)); return(Task.CompletedTask); }
public void QueueMp3Upload(SongUpload song, AlbumUpload album, int songNumber, string songId) { backgroundQueue.Enqueue(_ => TryUploadMp3(song, album, songNumber, songId)); }