public void Run() { // CountdownEvent(int initialCount) - 实例化一个 CountdownEvent // int initialCount - 初始计数 using (var countdown = new CountdownEvent(1)) { Thread t1 = new Thread(() => ThreadWork("aaa", TimeSpan.FromSeconds(1), countdown)); // 增加 1 个计数 countdown.AddCount(); t1.Start(); Thread t2 = new Thread(() => ThreadWork("bbb", TimeSpan.FromSeconds(2), countdown)); countdown.AddCount(); t2.Start(); Thread t3 = new Thread(() => ThreadWork("ccc", TimeSpan.FromSeconds(3), countdown)); countdown.AddCount(); t3.Start(); // 减少 1 个计数 countdown.Signal(); // 阻塞当前线程,直到 CountdownEvent 的计数为零 countdown.Wait(); } Console.WriteLine(_result); }
public void AddCount_Invalid() { using (var ev = new CountdownEvent(1)) { try { ev.AddCount(0); Assert.Fail("#1"); } catch (ArgumentOutOfRangeException ex) { Theraot.No.Op(ex); } try { ev.AddCount(-1); Assert.Fail("#2"); } catch (ArgumentOutOfRangeException ex) { Theraot.No.Op(ex); } } }
private static void colorRecord(object wb) { complete.AddCount(1); //ColorWriter.WriteVideoFrame((System.Drawing.Bitmap)wb); complete.Signal(); }
public void InitialTestCase() { Assert.AreEqual(5, evt.InitialCount, "#1"); evt.AddCount(); evt.Signal(3); Assert.AreEqual(5, evt.InitialCount, "#2"); }
public void TestCountEventTest() { var e = new CountdownEvent(0); e.Reset(2); e.AddCount(1); e.AddCount(1); }
private void BeginBuild(Category p) { sem.WaitOne(); countEventObject.AddCount(); Thread t = new Thread(new ParameterizedThreadStart(Build)); t.Start(p); }
public void MainThread() { m_Finisher.AddCount(); // Your stuff goes here. // myListener.BeginAcceptSocket(OnAcceptSocket, null); m_Finisher.Signal(); m_Finisher.Wait(); }
private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { Console.WriteLine(e.Data); OnOutputReceived?.Invoke(this, new StringEventArgs(e.Data)); } else { countdownEvent.AddCount(); } }
public void Run(int count, int spincount) { var cd = new CountdownEvent(1); var threads = new CountdownEvent(1); interlocked = new int[count]; monitored = new int[count]; for (var i = 0; i < count; i++) { var index = i; var tr = new Thread((o) => { // System.Console.WriteLine("reader {0}", index); var rnd = new Random(0); var sleep = 0; while (!cd.IsSet) { sleep = rollDice0(rnd, 3, 33); reader(index, sleep); sleep = rollDice0(rnd, 3, 33); Thread.Sleep(sleep); } // System.Console.WriteLine("reader {0} stopped", index); threads.Signal(); }); tr.IsBackground = true; tr.Start(); threads.AddCount(); var tw1 = new Thread((o) => { // System.Console.WriteLine("writer1 {0}", index); var rnd = new Random(0); var sleep = 0; while (!cd.IsSet) { writer(index, spincount); sleep = rollDice0(rnd, index, 10); Thread.Sleep(sleep); } // System.Console.WriteLine("writer1 {0} stopped", index); threads.Signal(); }); tw1.IsBackground = true; tw1.Start(); threads.AddCount(); } System.Console.WriteLine("Stopping in 30s ...."); Thread.Sleep(TimeSpan.FromSeconds(30)); cd.Signal(); threads.Signal(); threads.Wait(); }
public static void ForEach <T>(IEnumerable <T> source, Action <T> body) { if (source == null) { throw new ArgumentNullException("source"); } if (body == null) { throw new ArgumentNullException("body"); } var items = new List <T>(source); var countdown = new CountdownEvent(items.Count); WaitCallback callback = state => { try { body((T)state); } finally { countdown.AddCount(); } }; foreach (var item in items) { ThreadPool.QueueUserWorkItem(callback, item); } countdown.Wait(); }
private void ExecuteThreadedCompilePass(int threads) { using (var finished = new CountdownEvent(1)) { for (int threadID = 0; threadID < threads; threadID++) { finished.AddCount(); int tid = threadID; ThreadPool.QueueUserWorkItem( new WaitCallback(delegate { //try //{ CompileWorker(tid); //} //catch (Exception e) //{ // this.CompilerTrace.NewCompilerTraceEvent(CompilerEvent.Exception, e.ToString(), threadID); //} //finally //{ finished.Signal(); //} } )); } finished.Signal(); finished.Wait(); } }
// Validates init, set, reset state transitions. private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce) { CountdownEvent ev = new CountdownEvent(initCount); Assert.Equal(initCount, ev.InitialCount); // Increment (optionally). for (int i = 1; i < increms + 1; i++) { ev.AddCount(); Assert.Equal(initCount + i, ev.CurrentCount); } // Decrement until it hits 0. if (takeAllAtOnce) { ev.Signal(initCount + increms); } else { for (int i = 0; i < initCount + increms; i++) { Assert.False(ev.IsSet, string.Format(" > error: latch is set after {0} signals", i)); ev.Signal(); } } Assert.True(ev.IsSet); Assert.Equal(0, ev.CurrentCount); // Now reset the event and check its count. ev.Reset(); Assert.Equal(ev.InitialCount, ev.CurrentCount); }
public void Do() { const int FibonacciCalculations = 10; // One event is used for each Fibonacci object. CountdownEvent countdownEvent = new CountdownEvent(1); Fibonacci2[] fibArray = new Fibonacci2[FibonacciCalculations]; Random r = new Random(); // Configure and start threads using ThreadPool. Console.WriteLine("launching {0} tasks...", FibonacciCalculations); for (int i = 0; i < FibonacciCalculations; i++) { countdownEvent.AddCount(); Fibonacci2 f = new Fibonacci2(r.Next(20, 40), countdownEvent); fibArray[i] = f; ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i); } // Wait for all threads in pool to calculate. countdownEvent.Signal(); countdownEvent.Wait(); Console.WriteLine("All calculations are complete."); // Display the results. for (int i = 0; i < FibonacciCalculations; i++) { Fibonacci2 f = fibArray[i]; Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN); } }
private void FindMapsInDir(string path, CountdownEvent cntDwn) { var dirs = Directory.EnumerateDirectories(path); foreach (string d in dirs) { cntDwn.AddCount(); ThreadPool.QueueUserWorkItem(o => FindMapsInDir(d, cntDwn)); } var bzns = Directory.EnumerateFiles(path, "*.bzn"); foreach (string b in bzns) { Map m = LoadMap(b.Substring(0, b.LastIndexOf('.'))); lock (MAPS_LOCK) { if (m != null) { maps.Add(m); } } } cntDwn.Signal(); }
public void AddCountSignalStressTestCase() { var evt = new CountdownEvent(5); var count = 0; ParallelTestHelper.ParallelStressTest ( () => { var num = Interlocked.Increment(ref count); if (num % 2 == 0) { evt.AddCount(); } else { evt.Signal(); } }, 7 ); Assert.AreEqual(4, evt.CurrentCount, "#1"); Assert.IsFalse(evt.IsSet, "#2"); }
private void runWith(string groupId, Func <Task> callback) { Work work; lock (stateLock) { if (rwork.TryGetValue(groupId, out work)) { work.AddTask(callback); return; } work = new Work(groupId, callback); rwork.Add(groupId, work); activeWorkers.AddCount(); } Task.Run(async() => { try { await processWork(work); } finally { activeWorkers.Signal(); } }); }
private void ExecuteThreadedCompilePass(int threads) { using (var finished = new CountdownEvent(1)) { for (int threadID = 1; threadID <= threads; threadID++) { finished.AddCount(); int tid = threadID; ThreadPool.QueueUserWorkItem( new WaitCallback( delegate { CompileWorker(tid); finished.Signal(); } ) ); } finished.Signal(); finished.Wait(); } }
public void go(List <string> foundIpAddresses) { foundIps.Clear(); countdown = new CountdownEvent(1); List <string> ipBases = new List <string> { "192.168.1.", "192.168.0." }; foreach (string ipBase in ipBases) { for (int i = 1; i < 255; i++) { string ip = ipBase + i.ToString(); Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted); countdown.AddCount(); p.SendAsync(ip, 250, ip); //Console.WriteLine("sent ping {0}, signal je na {1}", ip, countdown.CurrentCount); } } countdown.Signal(); Console.WriteLine("sad je izmedju signal i wait"); countdown.Wait(); Console.WriteLine("zavrsio se wait"); Console.WriteLine("{0} hosts active.", upCount); foreach (string ip in foundIps) { Console.WriteLine("Jedna od nadjenih: {0}", ip); foundIpAddresses.Add(ip); } }
/// <summary> /// Called when [received completed]. /// </summary> /// <param name="message">The message.</param> private void ReceivedCompleted(byte[] message) { try { Logger.Debug("Channel Received Completed"); _semaphore.WaitOne(); _countdown.AddCount(); var thread = new Thread(() => { try { InvokeOnReceivedMessage(message); } catch (Exception exception) { Logger.Error("Error On Received Message", exception); } finally { _countdown.Signal(); _semaphore.Release(); } }); thread.Start(); } catch (Exception exception) { Logger.Error("Error Channel Received Completed", exception); throw; } }
static void Main(string[] args) { CountdownEvent ev = new CountdownEvent(1); Console.WriteLine("How many increment do you want to do ?"); int incCount = int.Parse(Console.ReadLine()); for (int i = 0; i < incCount; i++) { Console.WriteLine("Increment CountdownEvent"); ev.AddCount(); Console.WriteLine("CountdownEvent now at {0}", ev.CurrentCount); } Task.Factory.StartNew(() => { Console.WriteLine("Task started"); Console.WriteLine("Task task waiting for countdown"); ev.Wait(); Console.WriteLine("Task finished"); }); while (ev.CurrentCount > 0) { Console.WriteLine("Decrement by pressing any key"); Console.ReadKey(); ev.Signal(); Console.WriteLine("CountdownEvent now at {0}", ev.CurrentCount); } Console.WriteLine("End of program"); Console.Read(); }
/// <summary> /// Queues the specified work to run on the thread pool. /// </summary> /// <param name="function">The work to execute asynchronously</param> public void RunTask(Func <Task> function, bool validateConnected) { long taskId; function.AssertNotNull(nameof(function)); if (cancellationToken.IsCancellationRequested) { return; } if (validateConnected && MgmtSession.Instance.Context == null) { throw new PSInvalidOperationException(Resources.RunConnectSecMgmtAccount); } taskId = totalTaskCount; Interlocked.Increment(ref totalTaskCount); taskCounter.AddCount(); if (Interlocked.Read(ref activeTaskCount) < maxConcurrency) { RunConcurrentTaskAsync(taskId, function()); } else { taskQueue.Enqueue(new Tuple <long, Func <Task> >(taskId, function)); } }
// Grabs a snapshot of the current internal state, and starts a new task to send it to the server. private void StartFlush(EventBuffer buffer) { if (_disabled) { return; } FlushPayload payload = buffer.GetPayload(); if (payload.Events.Length > 0 || !payload.Summary.Empty) { lock (_flushWorkersCounter) { // Note that this counter will be 1, not 0, when there are no active flush workers. // This is because a .NET CountdownEvent can't be reused without explicitly resetting // it once it has gone to zero. if (_flushWorkersCounter.CurrentCount >= MaxFlushWorkers + 1) { // We already have too many workers, so just leave the events as is return; } // We haven't hit the limit, we'll go ahead and start a flush task _flushWorkersCounter.AddCount(1); } buffer.Clear(); Task.Run(() => FlushEventsAsync(payload)); } }
public void AddCount_Invalid() { var ev = new CountdownEvent(1); try { ev.AddCount(0); Assert.Fail("#1"); } catch (ArgumentOutOfRangeException) { } try { ev.AddCount(-1); Assert.Fail("#2"); } catch (ArgumentOutOfRangeException) { } }
static void Main() { // Initialize a queue and a CountdownEvent ConcurrentQueue <int> queue = new ConcurrentQueue <int>(Enumerable.Range(0, 10000)); CountdownEvent cde = new CountdownEvent(10000); // initial count = 10000 // This is the logic for all queue consumers Action consumer = () => { int local; // decrement CDE count once for each element consumed from queue while (queue.TryDequeue(out local)) { cde.Signal(); } }; // Now empty the queue with a couple of asynchronous tasks Task t1 = Task.Factory.StartNew(consumer); Task t2 = Task.Factory.StartNew(consumer); // And wait for queue to empty by waiting on cde cde.Wait(); // will return when cde count reaches 0 Console.WriteLine("Done emptying queue. InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet); // Proper form is to wait for the tasks to complete, even if you that their work // is done already. Task.WaitAll(t1, t2); // Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount // to the specified value cde.Reset(10); // AddCount will affect the CurrentCount, but not the InitialCount cde.AddCount(2); Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet); // Now try waiting with cancellation CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); // cancels the CancellationTokenSource try { cde.Wait(cts.Token); } catch (OperationCanceledException) { Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected"); } finally { cts.Dispose(); } // It's good for to release a CountdownEvent when you're done with it. cde.Dispose(); }
public bool WaitOne(int position = 0) { //CountdownEvent needs to have a initial count of 1 //otherwise it is created in signaled state position++; bool containsGrantedRequest = false; //flag to check if wait queue still contains object which owns the lock CountdownEvent thisRequest = position<1 ? new CountdownEvent(1) : new CountdownEvent(position); waitQueueSemaphore.WaitOne(); //insert the request at the appropriate position foreach (CountdownEvent cdEvent in waitQueue) { if (cdEvent.CurrentCount > position) cdEvent.AddCount(); else if (cdEvent.CurrentCount == position) thisRequest.AddCount(); if (cdEvent.CurrentCount == 0) containsGrantedRequest = true; } waitQueue.Add(thisRequest); //nobody holds the lock, so grant the lock to the current request if (containsGrantedRequest==false && thisRequest.CurrentCount == 1) thisRequest.Signal(); waitQueueSemaphore.Release(); thisRequest.Wait(); return true; }
public void StopsProcessingWhenExceptionThrown() { chunkProcessor.Start(cancellationTokenSource.Token); var inputThread = new Thread(() => { countdownEvent.AddCount(); var good = Memory <byte> .Empty; var faulty = Memory <byte> .Empty; processor.Setup(p => p.Process(good)).Returns(new ProcessedChunk(new byte[] { }, Memory <byte> .Empty)); inputQueue.Add(new FileChunk(ArrayPool <byte> .Shared.Rent(0), good)); processor.Setup(p => p.Process(faulty)).Throws <Exception>(); inputQueue.Add(new FileChunk(ArrayPool <byte> .Shared.Rent(0), faulty)); inputQueue.CompleteAdding(); countdownEvent.Signal(); }); inputThread.Start(); countdownEvent.Signal(); countdownEvent.Wait(); jobContextMock.Verify( // ReSharper disable once ExplicitCallerInfoArgument context => context.Failure(It.IsAny <Exception>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once); outputBufferMock.Verify(buffer => buffer.SubmitCompleted(), Times.Once); cancellationTokenSource.IsCancellationRequested.ShouldBeTrue(); }
/// <summary> /// Starts all delegates and waits they completed /// </summary> /// <param name="actions">Array delegates to process</param> /// <param name="objects">Data to be processed by delegates</param> public static void WaitAll(Action <object>[] actions, object[] objects) { if (actions.Length != objects.Length) { throw new ArgumentException("Argumets should have the same length"); } var data = new ActionData(actions, objects); using (var finished = new CountdownEvent(1)) { foreach (var a in data.Data) { finished.AddCount(); ThreadPool.QueueUserWorkItem(delegate { try { a.Item1(a.Item2); } finally { finished.Signal(); } }); } finished.Signal(); finished.Wait(); } }
public void AddCount_HasBeenSet() { using (var ev = new CountdownEvent(0)) { try { ev.AddCount(1); Assert.Fail("#1"); } catch (InvalidOperationException ex) { Theraot.No.Op(ex); } } using (var ev = new CountdownEvent(1)) { Assert.IsTrue(ev.Signal(), "#2"); try { ev.AddCount(1); Assert.Fail("#3"); } catch (InvalidOperationException ex) { Theraot.No.Op(ex); } } }
public async Task MessageQueueThread_HandlesException() { var exception = new Exception(); var countdown = new CountdownEvent(1); var handler = new Action <Exception>(ex => { Assert.AreSame(exception, ex); countdown.Signal(); }); var uiThread = await CallOnDispatcherAsync(() => MessageQueueThread.Create(MessageQueueThreadSpec.DispatcherThreadSpec, handler)); var backgroundThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("background", MessageQueueThreadKind.BackgroundSingleThread), handler); var taskPoolThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("any", MessageQueueThreadKind.BackgroundAnyThread), handler); var queueThreads = new[] { uiThread, backgroundThread, taskPoolThread }; countdown.AddCount(queueThreads.Length - 1); foreach (var queueThread in queueThreads) { queueThread.RunOnQueue(() => { throw exception; }); } Assert.IsTrue(countdown.Wait(5000)); }
void SnippetOne() { //<snippet01> IEnumerable <Data> source = GetData(); using (CountdownEvent e = new CountdownEvent(1)) { // fork work: foreach (Data element in source) { // Dynamically increment signal count. e.AddCount(); ThreadPool.QueueUserWorkItem(delegate(object state) { try { ProcessData(state); } finally { e.Signal(); } }, element); } e.Signal(); // The first element could be run on this thread. // Join with work. e.Wait(); } // .,. //</snippet01> } //end method
static void Main(string[] args) { countdown = new CountdownEvent(1); Stopwatch sw = new Stopwatch(); sw.Start(); foreach (var item in GetExternalIPAddress()) { string ipBase = item.ToString(); string[] ipParts = ipBase.Split('.'); ipBase = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "."; for (int i = 1; i < 255; i++) { string ip = ipBase + i.ToString(); Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted); countdown.AddCount(); p.SendAsync(ip, 100, ip); } } countdown.Signal(); countdown.Wait(); sw.Stop(); TimeSpan span = new TimeSpan(sw.ElapsedTicks); Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount); Console.ReadLine(); }
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 }