for (int i = 0; i < cde.CurrentCount; i++) { Task.Factory.StartNew(LoadProduct, i); } //等待所有任务执行完毕 cde.Wait(); Console.WriteLine("\nProduct表数据全部加载完毕!\n");
// 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 to release a CountdownEvent when you're done with it. cde.Dispose();
// A padding interval to make the output more orderly. privatestaticint padding;
publicstaticvoidMain() { // Create the semaphore. semaphore = new SemaphoreSlim(0, 3); 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(() => { // Each task begins by requesting the semaphore. Console.WriteLine("Task {0} begins and waits for the semaphore.", Task.CurrentId);
// Wait for half a second, to allow all the tasks to start and block. Thread.Sleep(500);
// Restore the semaphore count to its maximum value. Console.Write("Main thread calls Release(3) --> "); semaphore.Release(3);// 释放3次 Console.WriteLine("{0} tasks can enter the semaphore.", semaphore.CurrentCount); // Main thread waits for the tasks to complete. Task.WaitAll(tasks);
// Demonstrates: // ManualResetEventSlim construction w/ SpinCount // ManualResetEventSlim.WaitHandle privatestaticvoidMRES_SpinCountWaitHandle() { // Construct a ManualResetEventSlim with a SpinCount of 1000 // Higher spincount => longer time the MRES will spin-wait before taking lock ManualResetEventSlim mres1 = new ManualResetEventSlim(false, 1000); ManualResetEventSlim mres2 = new ManualResetEventSlim(false, 1000);
Task bgTask = Task.Factory.StartNew(() => { // Just wait a little Thread.Sleep(100);
// Now signal both MRESes Console.WriteLine("Task signalling both MRESes"); mres1.Set(); mres2.Set(); });
// A common use of MRES.WaitHandle is to use MRES as a participant in // WaitHandle.WaitAll/WaitAny. Note that accessing MRES.WaitHandle will // result in the unconditional inflation of the underlying ManualResetEvent. WaitHandle.WaitAll(new WaitHandle[] { mres1.WaitHandle, mres2.WaitHandle }); Console.WriteLine("WaitHandle.WaitAll(mres1.WaitHandle, mres2.WaitHandle) completed.");
// Clean up bgTask.Wait(); mres1.Dispose(); mres2.Dispose(); } } }