using System; using System.Threading; class Program { static void Main() { ManualResetEventSlim resetEvent = new ManualResetEventSlim(false); Thread t1 = new Thread(() => { Console.WriteLine("Thread 1 is waiting"); resetEvent.Wait(); Console.WriteLine("Thread 1 resumed"); }); Thread t2 = new Thread(() => { Console.WriteLine("Thread 2 is running"); resetEvent.Set(); }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } }
using System; using System.Threading; class Program { static void Main(string[] args) { int workerThreads = 5; ManualResetEventSlim[] resetEvents = new ManualResetEventSlim[workerThreads]; for (int i = 0; i < workerThreads; i++) { resetEvents[i] = new ManualResetEventSlim(false); ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), resetEvents[i]); } while (ManualResetEventSlim.WaitAll(resetEvents)) { Console.WriteLine("Batch complete"); for (int i = 0; i < workerThreads; i++) { resetEvents[i].Reset(); ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), resetEvents[i]); } } } static void DoWork(object state) { ManualResetEventSlim resetEvent = (ManualResetEventSlim)state; // Do some work here Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " is working..."); Thread.Sleep(1000); resetEvent.Set(); } }This code demonstrates how ManualResetEventSlim can be used to throttle the number of threads performing a task. In this example, there are five worker threads performing a task, and the code waits for all of them to complete before starting another batch of five threads. The ManualResetEventSlim objects are used to signal when each worker thread has completed its task. The ManualResetEventSlim class is part of the System.Threading.dll library, which is a core library included in the .NET Framework and .NET Core.