public static void CancelBeforeWait() { SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2); CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); CancellationToken ct = cs.Token; const int millisec = 100; TimeSpan timeSpan = new TimeSpan(100); EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait: An OCE should have been thrown."); EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); semaphoreSlim.Dispose(); }
public static bool CancelBeforeWait() { TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelBeforeWait()"); bool passed = true; SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2); CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); CancellationToken ct = cs.Token; const int millisec = 100; TimeSpan timeSpan = new TimeSpan(100); passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "An OCE should have been thrown."); passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "An OCE should have been thrown."); passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "An OCE should have been thrown."); semaphoreSlim.Dispose(); return passed; }
public async Task TheCompletePumpWithAsyncHandleMessage() { var runningTasks = new ConcurrentDictionary<Task, Task>(); var semaphore = new SemaphoreSlim(100); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var token = tokenSource.Token; int numberOfTasks = 0; var pumpTask = Task.Run(async () => { while (!token.IsCancellationRequested) { await semaphore.WaitAsync(token).ConfigureAwait(false); Interlocked.Increment(ref numberOfTasks); var task = HandleMessageWithCancellation(token); runningTasks.TryAdd(task, task); task.ContinueWith(t => { semaphore.Release(); Task taskToBeRemoved; runningTasks.TryRemove(t, out taskToBeRemoved); }, TaskContinuationOptions.ExecuteSynchronously) .Ignore(); } }); await pumpTask.IgnoreCancellation().ConfigureAwait(false); await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false); tokenSource.Dispose(); semaphore.Dispose(); $"Consumed {numberOfTasks} messages with concurrency {semaphore.CurrentCount} in 5 seconds. Throughput {numberOfTasks / 5} msgs/s" .Output(); }
public void Test() { SemaphoreSlim ss = new SemaphoreSlim(2); // se le indica que el thread se detendra 2 veces. Debug.Print("Constructed a SemaphoreSlim with an initial count of 2"); Debug.Print("First non-blocking Wait: {0} (should be true)", ss.Wait(0));//la primera vez que espera por 0 milisegundos. Debug.Print("Second non-blocking Wait: {0} (should be true)", ss.Wait(0));//la segunda vez. Debug.Print("Third non-blocking Wait: {0} (should be false)", ss.Wait(0));//aqui ya no se espera, aunque se haga wait, porque solo son dos veces. // Do a Release to free up a spot ss.Release();//con Release se puede esperar una vez mas a parte de las que ya tenia programadas.regresa un thread otra vez al pool., tenia 2 segun el constructor. Debug.Print("Non-blocking Wait after Release: {0} (should be true)", ss.Wait(0)); // Launch an asynchronous Task that releases the semaphore after 100 ms..asynchronous significa en otro hilo. Task t1 = Task.Factory.StartNew(() => { Thread.Sleep(100); Debug.Print("Task about to release SemaphoreSlim"); ss.Release(); }); // You can also wait on the SemaphoreSlim via the underlying Semaphore WaitHandle. // HOWEVER, unlike SemaphoreSlim.Wait(), it WILL NOT decrement the count. // In the printout below, you will see that CurrentCount is still 1 ss.AvailableWaitHandle.WaitOne(); Debug.Print("ss.AvailableWaitHandle.WaitOne() returned, ss.CurrentCount = {0}", ss.CurrentCount); // Now a real Wait(), which should return immediately and decrement the count. ss.Wait(); Debug.Print("ss.CurrentCount after ss.Wait() = {0}", ss.CurrentCount); // Clean up t1.Wait(); ss.Dispose(); }
public async Task CancellingAndGracefulShutdown() { #region Cancellation AsAbove var tokenSource = new CancellationTokenSource(); tokenSource.CancelAfter(TimeSpan.FromSeconds(1)); var token = tokenSource.Token; #endregion #region Task Tracking AsAbove var runningTasks = new ConcurrentDictionary<Task, Task>(); #endregion #region Limiting AsAbove var semaphore = new SemaphoreSlim(2); #endregion var pumpTask = Task.Run(async () => { while (!token.IsCancellationRequested) { #region Output "Pumping...".Output(); #endregion await semaphore.WaitAsync(token).ConfigureAwait(false); #region HandleMessage AsAbove var runningTask = HandleMessageWithCancellation(token); runningTasks.TryAdd(runningTask, runningTask); #endregion #region Releasing Semaphore & Housekeeping AsAbove runningTask.ContinueWith(t => { #region Output "... done".Output(); #endregion semaphore.Release(); #region Housekeeping Task taskToBeRemoved; runningTasks.TryRemove(t, out taskToBeRemoved); #endregion }, TaskContinuationOptions.ExecuteSynchronously) .Ignore(); #endregion } }, CancellationToken.None); await pumpTask.IgnoreCancellation().ConfigureAwait(false); #region Awaiting completion #region Output "Pump finished".Output(); #endregion await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false); #region Output "All receives finished".Output(); #endregion tokenSource.Dispose(); semaphore.Dispose(); #endregion }
public void Dispose() { _semaphore.Dispose(); }
public override async Task ExecuteAsync(CancellationToken cancellationToken) { if (string.IsNullOrEmpty(this._bucketName)) { throw new InvalidOperationException("The bucketName specified is null or empty!"); } SemaphoreSlim asyncThrottler = null; CancellationTokenSource internalCts = null; try { asyncThrottler = new SemaphoreSlim(_config.ConcurrentServiceRequests); internalCts = new CancellationTokenSource(); var internalCancellationToken = internalCts.Token; ListMultipartUploadsResponse listResponse = new ListMultipartUploadsResponse(); var pendingTasks = new List<Task<AbortMultipartUploadResponse>>(); do { ListMultipartUploadsRequest listRequest = ConstructListMultipartUploadsRequest(listResponse); listResponse = await this._s3Client.ListMultipartUploadsAsync(listRequest, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); foreach (MultipartUpload upload in listResponse.MultipartUploads) { cancellationToken.ThrowIfCancellationRequested(); if (internalCancellationToken.IsCancellationRequested) { // Operation cancelled as one of the AbortMultipartUpload requests failed with an exception, // don't schedule any more AbortMultipartUpload tasks. // Don't throw an OperationCanceledException here as we want to process the // responses and throw the original exception. break; } if (upload.Initiated < this._initiatedDate) { await asyncThrottler.WaitAsync(cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); var abortRequest = ConstructAbortMultipartUploadRequest(upload); var task = AbortAsync(abortRequest, internalCts, cancellationToken, asyncThrottler); pendingTasks.Add(task); } } } while (listResponse.IsTruncated); await WhenAllOrFirstExceptionAsync(pendingTasks,cancellationToken); } finally { if (internalCts != null) internalCts.Dispose(); if (asyncThrottler!=null) asyncThrottler.Dispose(); } }
/// <summary> /// Test SemaphoreSlim Dispose /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called after Dispose</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType) { Exception exception = null; SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { semaphore.Dispose(); CallSemaphoreAction(semaphore, action, null); } catch (Exception ex) { exception = ex; } // The code threw excption and it is not expected because the excyptionType param is null if (exceptionType == null && exception != null) { string methodFailed = "RunSemaphoreSlimTest4_Dispose(" + initial + "," + maximum + "," + action + "): FAILED. "; Assert.True(false, string.Format(methodFailed + "Dispose failed, the code threw an exception, and it is not supposed to.")); } // Compare both exception types in case of the code threw exception if (exception != null && !Type.Equals(exception.GetType(), exceptionType)) { string methodFailed = "RunSemaphoreSlimTest4_Dispose(" + initial + "," + maximum + "," + action + "): FAILED. "; Assert.True(false, string.Format(methodFailed + "Dispose failed, Excption types do not match")); } }
/// <summary> /// Call specific SemaphoreSlim method or property /// </summary> /// <param name="semaphore">The SemaphoreSlim instance</param> /// <param name="action">The action name</param> /// <param name="param">The action parameter, null if it takes no parameters</param> /// <returns>The action return value, null if the action returns void</returns> private static object CallSemaphoreAction (SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param) { if (action == SemaphoreSlimActions.Wait) { if (param is TimeSpan) { return semaphore.Wait((TimeSpan)param); } else if (param is int) { return semaphore.Wait((int)param); } semaphore.Wait(); return null; } else if (action == SemaphoreSlimActions.WaitAsync) { if (param is TimeSpan) { return semaphore.WaitAsync((TimeSpan)param).Result; } else if (param is int) { return semaphore.WaitAsync((int)param).Result; } semaphore.WaitAsync().Wait(); return null; } else if (action == SemaphoreSlimActions.Release) { if (param != null) { return semaphore.Release((int)param); } return semaphore.Release(); } else if (action == SemaphoreSlimActions.Dispose) { semaphore.Dispose(); return null; } else if (action == SemaphoreSlimActions.CurrentCount) { return semaphore.CurrentCount; } else if (action == SemaphoreSlimActions.AvailableWaitHandle) { return semaphore.AvailableWaitHandle; } return null; }
public Statistic RunExperiment(CalculationParameters param) { CheckParameters(param); var sw = Stopwatch.StartNew(); SimulatedGamesCount = 0; Card player_card1 = param.PlayerCard1; Card player_card2 = param.PlayerCard2; Card[] open_cards = GetOpenCards(param); ValidateInputCards(player_card1, player_card2, open_cards); Card[] cards = GetAllCards(); Card[] free_cards = GetFreeCards(cards, player_card1, player_card2, open_cards); var stat = new StatisticInternal(); stat.Init(); int parallelLevel = param.ParallelLevel; #if OneThreadForDBG parallelLevel = 1; #endif int enemyPlayersCount = param.EnemyPlayersCount; int gameNumber = param.GameNumber; var semaphore = new SemaphoreSlim(parallelLevel); var countdown = new CountdownEvent(gameNumber); for (int i = 0; i < gameNumber; i++) { param.CancelToken.ThrowIfCancellationRequested(); if (param.TimeLimit.HasValue && sw.Elapsed > param.TimeLimit.Value) { countdown.Signal(gameNumber - i); break; } semaphore.Wait(); SimulatedGamesCount++; Action action = () => { try { SimulateGame(player_card1, player_card2, open_cards, free_cards, enemyPlayersCount, stat, param); } finally { semaphore.Release(); countdown.Signal(); } }; if (parallelLevel == 1) { action(); } else { Task.Factory.StartNew(action); } } countdown.Wait(); countdown.Dispose(); semaphore.Dispose(); Statistic public_stat = PreparePublicStatistic(stat); return public_stat; }
/// <summary> /// Test SemaphoreSlim Dispose /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called after Dispose</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static bool RunSemaphoreSlimTest4_Dispose (int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType) { TestHarness.TestLog("Dispose(" + initial + "," + maximum + "," + action + ")"); Exception exception = null; SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { semaphore.Dispose(); CallSemaphoreAction(semaphore,action,null); } catch (Exception ex) { exception = ex; } // The code threw excption and it is not expected because the excyptionType param is null if (exceptionType == null && exception != null) { TestHarness.TestLog("Dispose failed, the code threw an exception, and it is not supposed to."); return false; } // Compare both exception types in case of the code threw exception if (exception != null && !Type.Equals(exception.GetType(), exceptionType)) { TestHarness.TestLog("Dispose failed, Excption types do not match"); return false; } TestHarness.TestLog("Dispose succeeded"); return true; }
private async Task ProcessAlertQueueAsync() { Logger.Instance.LogDebug("Starting alert processing."); DisplayAlertEvent currentAlert; do { lock (_lock) { var count = _alertQueue.Count; Logger.Instance.LogDebug("Alert queue contains {0} items", count); currentAlert = count == 0 ? null : _alertQueue.Peek(); } var semaphore = new SemaphoreSlim(0, 1); var viewEnabled = true; if (currentAlert != null) { var viewContainer = new StackLayout {Orientation = StackOrientation.Vertical}; viewContainer.GestureRecognizers.Add(new TapGestureRecognizer { NumberOfTapsRequired = 1, Command = new Command(() => { if (viewEnabled) { semaphore.Release(); } if (currentAlert.TapAction != null) { currentAlert.TapAction(); } }) }); currentAlert.Dismissed += (sender, args) => { if (viewEnabled) { semaphore.Release(); } }; viewContainer.Children.Add(currentAlert.Content); Device.BeginInvokeOnMainThread(() => _overlayContainer.Children.Add(viewContainer)); if (currentAlert.AutoDismiss) { var displayTime = currentAlert.DisplayTime ?? TimeSpan.FromSeconds(5); await semaphore.WaitAsync(displayTime); } else { await semaphore.WaitAsync(); } viewEnabled = false; Device.BeginInvokeOnMainThread(() => _overlayContainer.Children.Remove(viewContainer)); lock (_lock) { _alertQueue.Dequeue(); } semaphore.Dispose(); } } while (currentAlert != null); }