キューQueueの使用

6460 ワード

Documentクラス:
 class Document

    {

        public string Title { get; private set; }

        public string Content { get; private set; }



        public Document(string title, string content)

        {

            this.Title = title;

            this.Content = content;

        }

    }

DocumentManagerクラス:
class DocumentManager

    {

        private readonly Queue<Document> documentQueue = new Queue<Document>();



        public bool IsAvailable

        {

            get { return documentQueue.Count > 0; }

        }



        public void AddDocument(Document doc)

        {

            lock (this)

            {

                documentQueue.Enqueue(doc);

            }

        }



        public Document GetDocument()

        {

            Document doc = null;

            lock (this)

            {

                doc = documentQueue.Dequeue();

            }

            return doc;

        }

    }

ProcessDocumentsクラス:
class ProcessDocuments

    {

        private DocumentManager dm;

        protected ProcessDocuments(DocumentManager dm)

        {

            this.dm = dm;

        }



        protected void Run()

        {

            while (true)

            {

                if (dm.IsAvailable)

                {

                    Document doc = dm.GetDocument();

                    Console.WriteLine("processing document {0}", doc.Title);

                }

                Thread.Sleep(new Random().Next(20));

            }

        }



        public static void Start(DocumentManager dm)

        {

            new Thread(new ProcessDocuments(dm).Run).Start();

        }

    }

アプリケーション層:
class Program

    {

        static void Main(string[] args)

        {

            var dm = new DocumentManager();

            ProcessDocuments.Start(dm);

            for (int i = 0; i < 100; i++)

            {

                Document doc = new Document("Doc" + i.ToString(), "content");

                dm.AddDocument(doc);

                Console.WriteLine("Added document {0}", doc.Title);

                Thread.Sleep(new Random().Next(20));

            }



            Console.ReadLine();

        }

    }