Spawn Multiple Threads for work then wait until all finished

后端 未结 12 1556
遇见更好的自我
遇见更好的自我 2020-11-28 01:46

just want some advice on \"best practice\" regarding multi-threading tasks.

as an example, we have a C# application that upon startup reads data from various \"type

12条回答
  •  Happy的楠姐
    2020-11-28 01:56

    I like @Reed's solution. Another way to accomplish the same in .NET 4.0 would be to use a CountdownEvent.

    class Program
    {
        static void Main(string[] args)
        {
            var numThreads = 10;
            var countdownEvent = new CountdownEvent(numThreads);
    
            // Start workers.
            for (var i = 0; i < numThreads; i++)
            {
                new Thread(delegate()
                {
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                    // Signal the CountdownEvent.
                    countdownEvent.Signal();
                }).Start();
            }
    
            // Wait for workers.
            countdownEvent.Wait();
            Console.WriteLine("Finished.");
        }
    }
    

提交回复
热议问题