// Here, 20 threads are started with the SharedState object and are then joined to // wait untill all the threads have finished completing the task when the final output // is written. static void Main(string[] args) { int numThreads = 20; SharedState state = new SharedState(); Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new Thread(new Task(state).DoTheTask); threads[i].Start(); } for (int i = 0; i < numThreads; i++) { threads[i].Join(); } Console.WriteLine("Summarized value: {0}", state.State); Console.ReadKey(); }
public Task(SharedState sharedState) { this.state = sharedState; }