public static void CancelBeforeWait() { CountdownEvent countdownEvent = new CountdownEvent(2); CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); CancellationToken ct = cs.Token; const int millisec = 100; TimeSpan timeSpan = new TimeSpan(100); string message = "CancelBeforeWait: > Cancellation token does not match."; EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(ct), ct, message); EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(millisec, ct), ct, message); EnsureOperationCanceledExceptionThrown(() => countdownEvent.Wait(timeSpan, ct), ct, message); countdownEvent.Dispose(); }
//--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TSource currentElement, [AllowNull] ref TKey currentKey) { Debug.Assert(_source != null); bool moveNextResult = _source.MoveNext(ref currentElement !, ref currentKey); // There is special logic the first time this function is called. if (!_lookedForEmpty) { // Ensure we don't enter this loop again. _lookedForEmpty = true; if (!moveNextResult) { if (_partitionIndex == 0) { // If this is the 0th partition, we must wait for all others. Note: we could // actually do a wait-any here: if at least one other partition finds an element, // there is strictly no need to wait. But this would require extra coordination // which may or may not be worth the trouble. _sharedLatch.Wait(_cancelToken); _sharedLatch.Dispose(); // Now see if there were any other partitions with data. if (_sharedEmptyCount.Value == _partitionCount - 1) { // No data, we will yield the default value. currentElement = _defaultValue; currentKey = default(TKey) !; return(true); } else { // Another partition has data, we are done. return(false); } } else { // Not the 0th partition, we will increment the shared empty counter. Interlocked.Increment(ref _sharedEmptyCount.Value); } } // Every partition (but the 0th) will signal the latch the first time. if (_partitionIndex != 0) { _sharedLatch.Signal(); } } return(moveNextResult); }
public void Dispose() { Abort(true); if (_queue != null) { _queue.Dispose(); } if (_threadExit != null) { _threadExit.Dispose(); } }
public void AddItemsToTheMirrorCacheTest() { #region ASSEMBLE int totalCandidates = 5000; int totalInserts = 0; var random = new Random(); var data = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates)); CountdownEvent countdown = new CountdownEvent(1); TheMirrorCache <TheStorageEngineTSM> mirror; List <TheStorageEngineTSM> TSMs = new List <TheStorageEngineTSM>(); // Build the collection of TSMs foreach (var payload in data) { TSMs.Add(new TheStorageEngineTSM() { TXTPattern = payload.ToString() }); } // Spin up your mirror mirror = new TheMirrorCache <TheStorageEngineTSM>(10) { CacheStoreInterval = 1, IsStoreIntervalInSeconds = true, IsCachePersistent = true, UseSafeSave = true, AllowFireUpdates = true, }; #endregion #region ACT mirror.AddItems(TSMs, response => { totalInserts = response.Count(); countdown.Signal(); }); countdown.Wait(); countdown?.Dispose(); mirror?.Dispose(); #endregion #region ASSERT Assert.IsTrue(totalCandidates == totalInserts); #endregion }
static void Main(string[] args) { WriteLine("Starting two operations"); var t1 = new Thread(() => PerformOperation("Operation 1 is completed", 4)); var t2 = new Thread(() => PerformOperation("Operation 2 is completed", 8)); t1.Start(); t2.Start(); _countdown.Wait(); WriteLine("Both operations have been completed."); _countdown.Dispose(); }
public static void Run() { Console.WriteLine("开始"); var t1 = new Thread(() => PreformOperation("方法1 已经完成", 4)); var t2 = new Thread(() => PreformOperation("方法2 已经完成", 8)); t1.Start(); t2.Start(); _countdown.Wait(); Console.WriteLine("已经完成"); _countdown.Dispose(); }
public void Clean() { if (mre != null) { mre.Dispose(); mre = null; } if (countEvnt != null) { countEvnt.Dispose(); } }
public void SetAfterDisposeTest() { ParallelTestHelper.Repeat(delegate { Exception disp = null, setting = null; var evt = new CountdownEvent(2); var evtFinish = new CountdownEvent(2); ThreadPool.QueueUserWorkItem(delegate { try { evt.Signal(); evt.Wait(1000); _mre.Dispose(); } catch (Exception e) { disp = e; } evtFinish.Signal(); }); ThreadPool.QueueUserWorkItem(delegate { try { evt.Signal(); evt.Wait(1000); _mre.Set(); } catch (Exception e) { setting = e; } evtFinish.Signal(); }); var bb = evtFinish.Wait(1000); if (!bb) { Assert.AreEqual(true, evtFinish.IsSet); } Assert.IsTrue(bb, "#0"); Assert.IsNull(disp, "#1"); Assert.IsNull(setting, "#2"); evt.Dispose(); evtFinish.Dispose(); }); }
/// <summary> /// Download specified download group. /// </summary> /// <param name="groupName">The download group name.</param> /// <returns></returns> /// <exception cref="ClickOnceException"> /// An exception occurred during version update. /// </exception> /// <exception cref="OperationCanceledException"> /// Version update was canceled. /// </exception> public async Task <bool> DownloadFileGroupAsync(string groupName) { CountdownEvent countdown = null; bool result = false; void progress(object sender, DeploymentProgressChangedEventArgs e) { Notifier.Progress(new ClickOnceProgressInfo(e)); } void completed(object sender, AsyncCompletedEventArgs e) { Notifier.Complete(); if (e.Error != null) { throw new ClickOnceException(string.Format("An exception occurred while updating the version of group '{0}'. {1}", groupName, e.Error.Message), e.Error); } if (e.Cancelled) { throw new OperationCanceledException("Version update was canceled."); } result = true; countdown?.Signal(); } try { ApplicationDeployment.CurrentDeployment.DownloadFileGroupProgressChanged += progress; ApplicationDeployment.CurrentDeployment.DownloadFileGroupCompleted += completed; Notifier.Start(); countdown = new CountdownEvent(1); await Task.Run(() => ApplicationDeployment.CurrentDeployment.DownloadFileGroupAsync(groupName)).ConfigureAwait(false); countdown.Wait(); } finally { ApplicationDeployment.CurrentDeployment.DownloadFileGroupProgressChanged -= progress; ApplicationDeployment.CurrentDeployment.DownloadFileGroupCompleted -= completed; countdown?.Dispose(); } return(result); }
public void MainTest() { WriteLine("Starting two operations"); var t1 = new Thread(() => PerformOperation("Operation 1 is completed", 4)); var t2 = new Thread(() => PerformOperation("Operation 2", 8)); t1.Start(); t2.Start(); _countdown.Wait(); WriteLine("Both operations have been completed."); _countdown.Dispose(); Console.WriteLine(); }
public static void Excute() { Console.WriteLine("Starting two operations"); var t1 = new Thread(() => PerformOperation("Operation 1 is completed", 4)); var t2 = new Thread(() => PerformOperation("Operation 2 is completed", 8)); t1.Start(); t2.Start(); _countDown.Wait(); Console.WriteLine("Both operations have been completed"); _countDown.Dispose(); Console.ReadKey(); }
public void StopAll() { //There are no previously started workers if (_allStop == null) { return; } foreach (var w in _workers) { //Release the lock on the corresponding worker w.Item2.Set(); } //Wait for all workers to exit _allStop.Wait(); //Clear registery _workers.Clear(); //Release resources _allStop.Dispose(); _workDone.Dispose(); _allStop = _workDone = null; _job = null; }
public void TestAdd() { var item = new KeyValuePair <string, string>("1", "value"); var observableDictionary = PerformObservableDictionarySetup(new List <KeyValuePair <string, string> >()); var latch = new CountdownEvent(4); var collectionChangedActions = new List <NotifyCollectionChangedAction>(); var propertiesChanged = new List <string>(); void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args) { collectionChangedActions.Add(args.Action); latch?.Signal(); } void PropertyChangedHandler(object sender, PropertyChangedEventArgs args) { propertiesChanged.Add(args.PropertyName); latch?.Signal(); } observableDictionary.CollectionChanged += CollectionChangedHandler; observableDictionary.PropertyChanged += PropertyChangedHandler; observableDictionary.Add(item.Key, item.Value); latch.Wait(); Assert.Single(observableDictionary); var keys = new string[1]; observableDictionary.Keys.CopyTo(keys, 0); Assert.Equal("1", keys[0]); var values = new string[1]; observableDictionary.Values.CopyTo(values, 0); Assert.Equal("value", values[0]); Assert.Single(collectionChangedActions); Assert.Equal(NotifyCollectionChangedAction.Add, collectionChangedActions[0]); Assert.Equal(3, propertiesChanged.Count); Assert.Contains("Count", propertiesChanged); Assert.Contains("Keys", propertiesChanged); Assert.Contains("Values", propertiesChanged); latch.Dispose(); }
/// <summary> /// Update application version. /// </summary> /// <returns></returns> /// <exception cref="ClickOnceException"> /// An exception occurred during version update. /// </exception> /// <exception cref="OperationCanceledException"> /// Version update was canceled. /// </exception> public async Task <bool> UpdateAsync() { CountdownEvent countdown = null; bool result = false; void progress(object sender, DeploymentProgressChangedEventArgs e) { Notifier.Progress(new ClickOnceProgressInfo(e)); } void completed(object sender, AsyncCompletedEventArgs e) { Notifier.Complete(); if (e.Error != null) { throw new ClickOnceException("An exception occurred during version update. " + e.Error.Message, e.Error); } if (e.Cancelled) { throw new OperationCanceledException("Version update was canceled."); } result = true; countdown?.Signal(); } try { ApplicationDeployment.CurrentDeployment.UpdateProgressChanged += progress; ApplicationDeployment.CurrentDeployment.UpdateCompleted += completed; Notifier.Start(); countdown = new CountdownEvent(1); await Task.Run(() => ApplicationDeployment.CurrentDeployment.UpdateAsync()).ConfigureAwait(false); countdown.Wait(); } finally { ApplicationDeployment.CurrentDeployment.UpdateProgressChanged -= progress; ApplicationDeployment.CurrentDeployment.UpdateCompleted -= completed; countdown?.Dispose(); } return(result); }
public void TestTryAdd() { var latch = new CountdownEvent(4); var collectionChangedActions = new List <NotifyCollectionChangedAction>(); var propertiesChanged = new List <string>(); void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args) { collectionChangedActions.Add(args.Action); latch?.Signal(); } void PropertyChangedHandler(object sender, PropertyChangedEventArgs args) { propertiesChanged.Add(args.PropertyName); latch?.Signal(); } var observableDictionary = new ObservableConcurrentDictionary <string, string>(CollectionChangedHandler, PropertyChangedHandler); var success = observableDictionary.TryAdd("1", "value"); latch.Wait(); Assert.True(success); Assert.Single(observableDictionary); var keys = new string[1]; observableDictionary.Keys.CopyTo(keys, 0); Assert.Equal("1", keys[0]); var values = new string[1]; observableDictionary.Values.CopyTo(values, 0); Assert.Equal("value", values[0]); Assert.Single(collectionChangedActions); Assert.Equal(NotifyCollectionChangedAction.Add, collectionChangedActions[0]); Assert.Equal(3, propertiesChanged.Count); Assert.Contains("Count", propertiesChanged); Assert.Contains("Keys", propertiesChanged); Assert.Contains("Values", propertiesChanged); latch.Dispose(); }
public void SetPrivacyEqualToUnknown_GetPrivacyStatus_Returns_Unknown() { // setup latch = new CountdownEvent(1); string expectedPrivacyStatus = "UNKNOWN"; ACPCore.SetPrivacyStatus(MobilePrivacyStatus.Unknown); // test ACPCore.GetPrivacyStatus(new PrivacyStatusCallback()); latch.Wait(); latch.Dispose(); // verify Assert.That(retrievedPrivacyStatus, Is.EqualTo(expectedPrivacyStatus)); }
public void Dispose() { _isDisposed = true; _mre.Set(); _mre.Close(); _countEvt.Dispose(); _barrier.SignalAndWait(); CheckAllThreadsFinished(); _barrier.Dispose(); _mre = null; _workItems = null; }
public void Bar(Action printBar) { for (int i = 0; i < n; i++) { cd2.Wait(); printBar(); cd2.Dispose(); cd2 = new CountdownEvent(1); cd1.Signal(); } }
public void TestTearDown() { try { if (!_actionsCompleteEvent.Wait(ActionDelay.MultiplyBy(8))) { throw new TimeoutException("One of the actions is not able to finish in time."); } } finally { _actionsCompleteEvent.Dispose(); } }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { taskCounter?.Dispose(); } disposed = true; }
public void Foo(Action printFoo) { for (int i = 0; i < n; i++) { cd1.Wait(); printFoo(); cd1.Dispose(); cd1 = new CountdownEvent(1); cd2.Signal(); } }
public void GetCustomVisitorIdentifier_Gets_PreviouslySetCustomVisitorIdentifier() { // setup latch = new CountdownEvent(1); var expectedIdentifier = "someVisitorIdentifier"; ACPAnalytics.SetVisitorIdentifier(expectedIdentifier); // test ACPAnalytics.GetVisitorIdentifier(new VisitorIdentifierCallback()); latch.Wait(); latch.Dispose(); // verify Assert.That(retrievedVisitorIdentifier, Is.EqualTo(expectedIdentifier)); }
public static void CountDown() { WriteLine("start two operator"); var t1 = new Thread(() => { PerformOperator("Operator 1 is Completed", 4); }); var t2 = new Thread(() => { PerformOperator("Operator 2 is Completed", 8); }); t1.Start(); t2.Start(); countdownEvent.Wait(); WriteLine("Both Operator have been completed"); countdownEvent.Dispose(); }
/// <summary> /// Mutexの取得、開放タスク /// プロセス間で1多重にするために1スレッドをシグナル処理する。 /// なお超絶遅いので頻繁にMutexでなにかするのには向いていない。 /// (プロセス跨がないのならlockステートメントなりセマフォなりで良い) /// </summary> private void MutexControlTask() { // Mutex取得開始 waitResult = instance.WaitOne(); waitEndEvent.Signal(); // Mutexの開放まで待機 releaseEvent.Wait(); releaseEvent.Dispose(); // Mutex開放 instance.ReleaseMutex(); instance.Dispose(); instance = null; }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (mutexControll != null) { releaseEvent.Signal(); } waitStartEvent.Dispose(); waitEndEvent.Dispose(); disposedValue = true; } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { cde.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public void TestGetUrlVariables_Returns_UrlVariables() { // setup latch = new CountdownEvent(2); string orgid = "972C898555E9F7BC7F000101%40AdobeOrg"; // test ACPIdentity.GetExperienceCloudId(new EcidCallback()); ACPIdentity.GetUrlVariables(new StringCallback()); latch.Wait(); latch.Dispose(); // verify Assert.That(retrievedString, Is.StringContaining(retrievedEcid)); Assert.That(retrievedString, Is.StringContaining(orgid)); }
public void Ex1_SemaphoreSlim() { // Create the semaphore. semaphore = new SemaphoreSlim(initialCount: 0, maxCount: 3); CountdownEvent cde = new CountdownEvent(5); Console.WriteLine("{0} tasks can enter the semaphore.", semaphore.CurrentCount); Task[] tasks = new Task[5]; // Create and start five numbered tasks. for (int i = 0; i <= 4; i++) { tasks[i] = Task.Run(() => { cde.Signal(); // Each task begins by requesting the semaphore. Console.WriteLine("Task {0} begins and waits for the semaphore.", Task.CurrentId); semaphore.Wait(); Interlocked.Add(ref padding, 100); Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId); // The task just sleeps for 1+ seconds. Thread.Sleep(1000 + padding); Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.", Task.CurrentId, semaphore.Release()); }); } // Wait for all the tasks to start and block. cde.Wait(); // Restore the semaphore count to its maximum value. Console.Write("Main thread calls Release(3) --> "); semaphore.Release(3); Console.WriteLine("{0} tasks can enter the semaphore.", semaphore.CurrentCount); // Main thread waits for the tasks to complete. Task.WaitAll(tasks); semaphore.Dispose(); cde.Dispose(); Console.WriteLine("Main thread exits."); }
/// <summary> /// <see cref="IDevice.RemoveSegmentAsync(int, AsyncCallback, IAsyncResult)"/> /// </summary> /// <param name="segment"></param> /// <param name="callback"></param> /// <param name="result"></param> public override void RemoveSegmentAsync(int segment, AsyncCallback callback, IAsyncResult result) { var countdown = new CountdownEvent(partitions.Devices.Count); foreach (IDevice shard in partitions.Devices) { shard.RemoveSegmentAsync(segment, ar => { if (countdown.Signal()) { callback(ar); countdown.Dispose(); } }, result); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { handle?.Dispose(); _countdown.Dispose(); } _disposed = true; }
/* * public SharedMessage<TU> ShareMsg<TU>() where TU : IMessage, IDisposable * { * return new ((TU) (IMessage) Message, cd); * } */ public void Dispose() { if (disposed) { return; } disposed = true; if (!cd.Signal()) { return; } Message.Dispose(); cd.Dispose(); }
public static void RunCountdownEventTest2_Exceptions() { CountdownEvent cde = null; Assert.Throws<ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1)); // Failure Case: Constructor didn't throw AORE when -1 passed cde = new CountdownEvent(1); Assert.Throws<ArgumentOutOfRangeException>(() => cde.Signal(0)); // Failure Case: Signal didn't throw AORE when 0 passed cde = new CountdownEvent(0); Assert.Throws<InvalidOperationException>(() => cde.Signal()); // Failure Case: Signal didn't throw IOE when the count is zero cde = new CountdownEvent(1); Assert.Throws<InvalidOperationException>(() => cde.Signal(2)); // Failure Case: Signal didn't throw IOE when the signal count > current count Assert.Throws<ArgumentOutOfRangeException>(() => cde.AddCount(0)); // Failure Case: AddCount didn't throw AORE when 0 passed cde = new CountdownEvent(0); Assert.Throws<InvalidOperationException>(() => cde.AddCount(1)); // Failure Case: AddCount didn't throw IOE when the count is zero cde = new CountdownEvent(int.MaxValue - 10); Assert.Throws<InvalidOperationException>(() => cde.AddCount(20)); // Failure Case: AddCount didn't throw IOE when the count > int.Max cde = new CountdownEvent(2); Assert.Throws<ArgumentOutOfRangeException>(() => cde.Reset(-1)); // Failure Case: Reset didn't throw AORE when the count is zero Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(-2)); // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1))); // Failure Case: FAILED. Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue)); // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken())); // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken())); // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max cde.Dispose(); Assert.Throws<ObjectDisposedException>(() => cde.Wait()); // Failure Case: Wait() didn't throw ODE after Dispose }