using …

Pure C#

‘Design Pattern’ Kategorisi için Arşiv

How to: Implement a Parallel Producer-Consumer Pattern

Yazan: esersahin 14/08/2009

http://msdn.microsoft.com/en-us/library/dd460684(VS.100).aspx

This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

The following examples show how to use the thread-safe System.Collections.Concurrent..::.BlockingCollection<(Of <(T>)>) collection class to implement the producer-consumer pattern. In this pattern, one or more producer threads add items to a collection as other consumer threads remove items from it. The examples also show how to cancel the producer thread.

C#
namespace ProducerConsumer
{
    using System;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    class Program
    {

        // Limit the collection size to 2000 items
        // at any given time.
        const int upperLimit = 2000;

        static BlockingCollection<long> collection = new BlockingCollection<long>(upperLimit);

        // Variables for diagnostic output only.
        static Stopwatch sw = new Stopwatch();
        static int additions = 0;
        static int subtractions = 0;

        static void Main(string[] args)
        {

            // Start the stopwatch.
            sw.Start();

            // Queue the ProduceData thread.
            ThreadPool.QueueUserWorkItem(new WaitCallback(RunProducer));

            // Queue the ConsumeData thread.
            ThreadPool.QueueUserWorkItem(new WaitCallback(RunConsumer));
            // ThreadPool.QueueUserWorkItem(new WaitCallback(RunConsumer2));

            // Keep the console window open while the
            // consumer thread completes its output.
            Console.ReadKey();

        }

        static void RunProducer(Object stateInfo)
        {

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

                long ticks = sw.ElapsedTicks;

                // Uncomment this line to see interleaved additions and subtractions.
                Console.WriteLine("adding tick value {0}. item# {1}", ticks, additions);

                collection.Add(ticks);

                // Counter for demonstration purposes only.
                additions++;

                // For demonstration purposes, uncomment this line to 
                // slow down the producer thread without sleeping.

                // Thread.SpinWait(100000); 

            }

            // Important!!! Tell consumers that no more items will be added.
            collection.CompleteAdding();

            Console.WriteLine("Done adding: {0} items", additions);
        }

        static void RunConsumer(Object stateInfo)
        {
            // GetConsumingEnumerable returns the enumerator for the 
            // underlying collection.
            foreach (var item in collection.GetConsumingEnumerable())
            {
                Console.WriteLine("Consuming tick value {0} : item# {1} ",
                        item.ToString("D18"), subtractions++);
            }

            Console.WriteLine("Total added: {0} Total consumed: {1} Current count: {2} ",
                                additions, subtractions, collection.Count());
            sw.Stop();

            Console.WriteLine("Press any key to exit");
        }

        static void RunConsumer2(Object stateInfo)
        {
            // Count may be zero while still waiting for more items.
            // IsCompleted may be true while Count is still > 0.
            // Therefore, iterate as long as either condition is true.
            while (collection.IsCompleted == false || collection.Count > 0)
            {
                long ticks = 0;
                bool b = collection.TryTake(out ticks, 30);
                if (b == true)
                {
                    Console.WriteLine("Consuming {0} : {1} ", ticks.ToString("D18"), subtractions++);
                }
                else
                {
                    // Do something else useful before trying again.
                    Console.WriteLine("Doing something useful here");
                }
            }

            Console.WriteLine("Total added: {0} Total consumed: {1} Current count: {2} ",
                                additions, subtractions, collection.Count);
        }
    }
}

System.Collections.Concurrent..::.BlockingCollection<(Of <(T>)>) limits the maximum number of items that are in the collection at any time. It also blocks consumer threads if no items are available and it blocks producer threads if the collection is full. This example uses a foreach loop with the BlockingCollection<(Of <(T>)>)..::.GetConsumingEnumerable method in the consuming thread. This type of loop blocks if the collection is empty. In this example blocking is not a concern because the producer thread adds items faster than they can be consumed. The second example in this topic shows how a consumer thread can perform other work if the collection is empty.

The producer thread reads the ElapsedTicks property of a Stopwatch instance and adds that value to the collection. The consumer thread removes items from the collection and simply prints the value to the console. (The call to WriteLine slows down the consumer thread significantly. Remember, this is just an example.) If no upper bound were specified in the System.Collections.Concurrent..::.BlockingCollection<(Of <(T>)>) constructor, the collection would grow and consume all system memory. To see this for yourself, remove the argument from the constructor, press F5, and view the process in Task Manager.

The following example shows how to consume the collection in such a way that the consuming thread can perform other work if the collection is empty. This is useful in scenarios where the producer is generally slower than the consumer thread.

C#
static void RunConsumer2(Object stateInfo)
{
    // Count may be zero while still waiting for more items.
    // IsCompleted may be true while Count is still > 0.
    // Therefore, iterate as long as either condition is true.
    while (collection.IsCompleted == false || collection.Count > 0)
    {
        long ticks = 0;
        bool b = collection.TryTake(out ticks, 30);
        if (b == true)
        {
            Console.WriteLine("Consuming {0} : {1} ", ticks.ToString("D18"), subtractions++);
        }
        else
        {
            // Do something else useful before trying again.
            Console.WriteLine("Doing something useful here");
        }
    }

    Console.WriteLine("Total added: {0} Total consumed: {1} Current count: {2} ",
                        additions, subtractions, collection.Count);
}

To compile and run this code, cut and paste it into the previous example, and then comment out the first QueueUserWorkItem method call, and uncomment the second call. Next, uncomment the SpinWait lines in the RunProducer method to simulate a slow producer thread.

Yazı kategorisi: Design Pattern, Producer-Consumer Pattern | » yorum bırak;

Foundations of Object-Oriented Programming Using .NET 2.0 Patterns

Yazan: esersahin 13/08/2009

http://www.apress.com/book/view/1590595408

Yazı kategorisi: Design Pattern | » yorum bırak;

C# 3.0 Design Patterns

Yazan: esersahin 13/08/2009

http://patterns.cs.up.ac.za/

http://oreilly.com/catalog/9780596527730/

Yazı kategorisi: Design Pattern | » yorum bırak;

Microsoft® .NET: Architecting Applications for the Enterprise

Yazan: esersahin 07/06/2009

http://www.amazon.com/Microsoft%C2%AE-NET-Architecting-Applications-PRO-Developer/dp/073562609X/ref=pd_sim_b_7

I have enjoyed reading this book and highly recommend it.

Great book,excellent reference…

Yazı kategorisi: Dependency Injection, Design Pattern, Domain Driven Design, Enterprise Library, Entity, Loose Coupling, MVC, Model View Presenter, NHibernate, Pattern & Practices, Web Client Software Factory, Web Service Software Factory | » yorum bırak;

David Hayden on Design Patterns C#

Yazan: esersahin 17/05/2009

http://davidhayden.com/blog/dave/category/22.aspx?Show=All

Day of Patterns & Practices Tomorrow – Tampa, Florida RoadShow

posted @ Wednesday, January 30, 2008 10:02 AM | Feedback (0)

Software Development Tip: Avoid Race Conditions Using Tester-Doer Pattern

One of the patterns that came up today in a code review was the Tester-Doer Pattern. One sees this pattern a lot especially when the “doer” side of the equation has a pretty decent performance penalty. Essentially, you test a condition to make sure you need to do the “doer“ operation and pay that penalty. Sometimes this can cause race conditions. Read more…

posted @ Wednesday, September 26, 2007 9:49 PM | Feedback (0)

Chain of Responsibility Pattern – Builder Pattern – Fluent Interfaces

Using the Chain of Responsibility Pattern, Builder Pattern, and Fluent Interfaces to find the appropriate constructor to inject dependencies into as part of the sample Dependency Injection Application Block I created using the Application Block Software Factory in Enterprise Library 3.1. Read more…

posted @ Wednesday, September 19, 2007 4:21 PM | Feedback (0)

Model View Presenter Pattern – User Interface Design Patterns

posted @ Wednesday, September 13, 2006 5:27 PM | Feedback (0)

Contract-First-Design and Dependency Injection ( Microkernel )

posted @ Tuesday, September 05, 2006 7:00 PM | Feedback (0)

O/R Mapping Caching for Performance vs. Uniquing ( Identity Map Design Pattern )

posted @ Tuesday, September 05, 2006 11:38 AM | Feedback (0)

Active Record To Domain Objects and Data Access Objects – Data Access Design Patterns

posted @ Friday, September 01, 2006 2:48 PM | Feedback (0)

Active Record Design Pattern Doesn’t Require Static Finder Methods

posted @ Friday, September 01, 2006 11:21 AM | Feedback (0)

Dependency Injection Tools and Inversion of Control – Applying Domain-Driven Design and Patterns

posted @ Friday, July 21, 2006 1:16 PM | Feedback (0)

Agile Principles, Patterns, and Practices in C# by Robert Martin

I just got back from a long and much needed vacation. While spending most of the day trying to make a dent in my Inbox, I came across an email from Amazon mentioning a new book from Robert Martin, called Agile Principles, Patterns, and Practices in C#…

posted @ Monday, July 03, 2006 11:34 PM | Feedback (0)

Domain-Driven Design Using Active Record in .NET

posted @ Wednesday, June 21, 2006 8:56 PM | Feedback (0)

ActiveRecord Example and Object-Relational Mapping Anti-Pattern – Not Always So Cut and Dry

posted @ Wednesday, June 14, 2006 2:03 PM | Feedback (0)

DLinq, LLBLGen Pro, and ActiveRecord Examples using ASP.NET 2.0

posted @ Monday, June 12, 2006 3:57 PM | Feedback (0)

Castle ActiveRecord – Active Record Pattern Built on NHibernate – ASP.NET C#

posted @ Monday, June 12, 2006 12:15 PM | Feedback (0)

ActiveRecord Pattern and Layer Supertype – Domain Model and Domain-Driven Design

posted @ Sunday, June 11, 2006 10:06 PM | Feedback (0)

Active Record Design Pattern – Domain Driven Design and Domain Layer – Object Persistence

posted @ Saturday, June 10, 2006 10:28 PM | Feedback (0)

Singleton Design Pattern and ReaderWriterLock Class in CLR via C# – Design Pattern Examples

posted @ Tuesday, June 06, 2006 10:50 AM | Feedback (0)

Abstract Factory Design Pattern – DbProviderFactory – Factory Method

posted @ Tuesday, April 04, 2006 4:51 PM | Feedback (0)

OOP and Design Patterns Resources – Books Websites Articles

posted @ Tuesday, March 14, 2006 9:45 PM | Feedback (0)

.NET 2.0 Provider Model – Polymorphism – Factory Method – ADO.NET 2.0 Data Providers

posted @ Sunday, October 30, 2005 7:22 PM | Feedback (0)

Builder Design Pattern Part 2 – Hotel Reservation EDI Example – Design Patterns in C#

posted @ Wednesday, October 26, 2005 7:07 PM | Feedback (0)

Builder Design Pattern Part I – DBConnectionStringBuilder and SqlConnectionStringBuilder in ADO.NET 2.0

posted @ Tuesday, October 25, 2005 1:59 PM | Feedback (0)

Web Applications: N-Tier vs. N-Layer – Benefits and Trade-Offs

posted @ Friday, July 22, 2005 2:06 PM | Feedback (1)

Strategy Design Pattern and Open-Closed Principle

posted @ Friday, July 01, 2005 5:22 PM | Feedback (0)

Strategy Design Pattern and Dependency-Inversion Principle

posted @ Monday, June 27, 2005 7:54 PM | Feedback (0)

Design Patterns in the .NET Framework – Adapter Factory Strategy Composite Template Method

posted @ Thursday, June 16, 2005 7:28 PM | Feedback (2)

Design Patterns and Agile Software Development

posted @ Friday, May 27, 2005 4:09 PM | Feedback (3)

Singleton Pattern in C# – Provider Model – Community Server and DotNetNuke

posted @ Wednesday, April 27, 2005 9:06 PM | Feedback (6)

DotNetNuke Architecture – Digging Into the DNN Source Code

posted @ Sunday, April 03, 2005 10:31 PM | Feedback (6)

Design Patterns in C# – Construction Pattern – Factory Method

posted @ Saturday, April 02, 2005 10:42 PM | Feedback (3)

GRASP Patterns – Information Expert – Create a Shopping Cart

posted @ Sunday, March 27, 2005 5:08 PM | Feedback (4)

PatternShare – Design Patterns Shared by .NET Architects and .NET Developers – Software Patterns

posted @ Saturday, February 05, 2005 8:06 PM | Feedback (1)

Command-Query Separation Principle Revisted – C# Int32.TryParse – Telling vs. Asking – Code Reading and Refactoring

posted @ Sunday, January 16, 2005 1:44 PM | Feedback (1)

Applying UML and Patterns – Command Query Separation Principle – GRASP Patterns – Ecommerce and Shopping Cart

posted @ Saturday, January 15, 2005 7:56 PM | Feedback (2)

Refactoring to Patterns – Thoughts on Test-Driven Development and Design Patterns and Extreme Programming

posted @ Sunday, December 19, 2004 12:04 PM | Feedback (2)

Domain-Driven Design – Layered Applications – More on High Cohesion and Separation of Concerns

posted @ Sunday, December 12, 2004 10:19 AM | Feedback (7)

Applying UML and Patterns – GRASP High Cohesion Pattern – Described using Controller and Creator GRASP Patterns

posted @ Friday, December 10, 2004 9:00 PM | Feedback (12)

Refactoring – Code Smells – Refactoring Patterns – Object Design – Somewhat Like Database Normalization

posted @ Thursday, December 09, 2004 1:23 PM | Feedback (14)

Applying UML and Patterns: Controller GRASP Pattern – Model View Controller Design Pattern – First Object Beyond UI Layer

posted @ Sunday, November 28, 2004 8:58 PM | Feedback (11)

.NET Application Development Guidelines – Factories vs. Constructors

posted @ Sunday, October 24, 2004 7:05 PM | Feedback (1)

Provider Model Design Pattern and Specification – ASP.NET Whidbey – Visual Studio 2005 – Design Patterns C#

posted @ Wednesday, May 19, 2004 12:21 PM | Feedback (4)

Design Patterns in C# Book – Sarasota Website Development – Florida

posted @ Tuesday, May 18, 2004 8:56 PM | Feedback (5)

Design Patterns C# .NET – Strategy Observer Adapter Singleton Template Method Wrapper Facade – Tampa Web Developer – Florida

posted @ Monday, May 17, 2004 8:55 AM | Feedback (4)

Yazı kategorisi: C#, Design Pattern | » yorum bırak;