Пример #1
0
        // Thread code for the consumer
        public void run()
        {
            // While not finished, dequeue a work item from the PCQueue and consume this work item by invoking
            // its ReadData() method and then outputting to the console a message to show this has happened
            while (!Finished)
            {
                // Dequeue a work item
                var item = pcQueue.dequeueItem();

                if (!ReferenceEquals(null, item))
                {
                    // Invoke the work item's ReadData() method, which returns a constituency
                    Location constituency = item.ReadData();

                    // Ensure null returns are ignored (will happen if data not in correct format or can't open file)
                    if (!ReferenceEquals(null, constituency))
                    {
                        // Add this constituency to the constituency list (lock it while modifying)
                        lock (constituencyList)
                        {
                            constituencyList.Locations.Add(constituency);
                        }
                        // Output to the console
                        Console.WriteLine("Consumer:{0} has consumed Work Item:{1}", id, item.configRecord.ToString());
                    }
                    else
                    {
                        // Output to the console
                        Console.WriteLine("Consumer:{0} has rejected Work Item:{1}", id, item.configRecord.ToString());
                    }

                    // Simulate consumer activity running for duration milliseconds
                    Thread.Sleep(duration);

                    lock (locker)
                    {
                        progManager.ItemsRemaining--;
                    }
                }
            }

            // Decrement the number of running consumer threads
            lock (locker)
            {
                RunningThreads--;
            }

            // Output that this consumer has finished
            Console.WriteLine("Consumer:{0} has finished", id);
        }