Monday, November 28, 2016

Parallel.For and Parallel.Foreach – Task Parallel Library


Task Parallel Library provides Parallel.For and Parallel.Foreach methods to achieve data parallelism. Data parallelism refers to scenario where you can perform operation in parallel. The Parallel.For and Parallel.foreach methods are part of System.Threading.Tasks.Parallel.

Sequential loop like below -

for(int i=0; i<10; i++)
     Console.Write("{0},",i);

Output -
0,1,2,3,4,5,6,7,8,9,


Parallel for loop –

Parallel.For(0, 10, i => Console.Write("{0},",i));

Output –
2,3,4,8,9,1,7,6,5,0,


Parallel foreach loop - 

List<int> numbers = new List<int>() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Parallel.ForEach(numbers, x => Console.Write("{0},", x));

Output –
2,3,5,7,9,1,8,4,6,0,

As we all know about how sequential loop works. But when parallel loop executes, the task parallel library partitioned data into multiple parts and loop can iterate on multiple parts concurrently. Internally task scheduler of TPL partitioned data and distribute data between multiple threads if required. So you can see the output of parallel for loop is different than sequential for loop. With parallel loop, order of data is not guaranteed because task parallel library divides data in multiple parts and process it in parallel.

Parallel For and Foreach loops gives you best performance via utilizing the multiple cores of your machine. Developer can use parallel loops to leverage full potential of the available hardware. Task parallel Library internally manages code to adjust with different cores and hardware without changing it. If you running parallel loops with single core machine this will use single core to run parallel loops and takes bit more time compare to run the same on four core machine. See below image where parallel loop utilizes four cores of your machine equally to complete its operation.





How to break parallel loops in between?


We normally break sequential loops using break keyword like below.

for (int i = 0; i < 500; i++)
{
    if (i == 100)
        break;
    Console.Write("{0},", i);
}

But you can’t use break with Parallel loops. There is different way to break parallel loop on some condition. If you want to break parallel loop, then you need to use different overload methods of Parallel for and foreach where delegate accepts ParallelLoopState like below.

public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body);

See below example to break parallel loops -

Parallel.For(0, 10, (int i, ParallelLoopState loopstate) =>
{
    if (i == 5)
    {
       loopstate.Break();
return;
    }

    Console.Write("{0},", i);
});

Output –
8,4,2,6,3,0,1,

As you can see in output when variable ‘i’ value is 5, loop will break. But in parallel loops the order is not guaranteed because task parallel library divides data in multiple parts and run concurrently.

If you break loop in between means loop is not completed fully. You can check status whether loop is completed or not using ParallelLoopResult. ParallelLoopResult is return type for almost all Paralle.For and Parallel.Foreach overload methods. ParallelLoopResult can also be used to know the value of LowestBreakIteration (loop break value). See below example to check whether loop is completed or not or break in between.

ParallelLoopResult result = Parallel.For(0, 10,(int i, ParallelLoopState loopstate) =>
{
    if (i == 5)
    {
        loopstate.Break();
        return;
    }
    Console.Write(string.Format("{0},", i));
});
if (result.IsCompleted)
    Console.WriteLine("Loop fully completed.");
else if (result.LowestBreakIteration.HasValue)
    Console.WriteLine("Loop not fully completed. Broken at value {0}", result.LowestBreakIteration.Value);

Output –
2,3,4,6,1,8,0,
Loop not fully completed. Broken at value 5


I hope this article helps you to know more about Parallel.For and Paralle.Foreach methods of Parallel extension of Task Parallel Library. Please leave your feedback in comments below.


Reference –

See also – 

Wednesday, October 26, 2016

Proxy Pattern


Proxy pattern provides placeholder for another object to access it. It provides wrapper and delegation to protect actual object and its complexity from end user. Proxy pattern falls under structural pattern of GOF (Gang of Four) pattern.

When to use –


Proxy pattern can be used when you want to access remote object using local object. The remote object can be from network, file, service or any other object. Proxy acts as wrapper for simplifying complex objects and provides simpler way to access it. Proxy can also be used to provide additional functionality over actual object without changing real object’s code like adding thread safety to actual object.

Below are types of proxy.
  • Virtual Proxy – This type of proxy can be used to create objects that are heavy and complex. So using virtual proxy you can create them on demand.
  • Remote Proxy – This type of proxy provides local interface for an object that is in remote location (in different address space). The example of remote proxy is the use of WCF/Web service where client accessing remote code located on different server on different network.
  • Protection Proxy – This type of proxy can be used when you want add authentication mechanism for client to access real object.
  • Smart Proxy – This type of proxy can be used to add additional functionality to manage resources efficiently. For example, counting number of references to real object, making real object thread safe etc.

Major components of Proxy pattern –


Subject – This is an interface provides abstract methods to access using proxy class.
Real Subject – This is concrete class which implements subject interface.
Proxy – This is proxy class and used by client to access real object. Proxy class has reference to actual object and resources.

See below example of proxy pattern.

Code –
//subject
public interface IPayment
{
    void PayAmount(double amount);
}
//real subject
public class CashPayment : IPayment
{
    public void PayAmount(double amount)
    {
        Console.WriteLine("The amount of Rs. {0} paid in cash", amount);
    }
}
//proxy class
public class CardPayment : IPayment
{
    CashPayment cashPay;
    public void PayAmount(double amount)
    {
        if (cashPay == null)
            cashPay = new CashPayment();

        cashPay.PayAmount(amount);
    }
}
//client
class Program
{
    static void Main(string[] args)
    {
        IPayment payment = new CardPayment();
        payment.PayAmount(5000);
        Console.ReadLine();
    }
}

Output –



As you can see in above example, CardPayment class acts as proxy class. CardPayment class has referent to real object which is CashPayment. So whenever you pay amount using CardPayment proxy class which actually pay amount from real object which is CashPayment. So CardPayment class acts as intermediate/wrapper between CashPayment and Client.

I hope this article helps you to know more about Proxy Pattern. Please leave your feedback in comments section below.

References –

See Also –


Sunday, September 25, 2016

Flyweight Pattern


Flyweight pattern allow us to reuse memory space via reducing similar kind of object creation. Flyweight pattern falls under structural pattern of GOF (Gang of Four) patterns.

When to use –


Flyweight pattern can be used in scenarios where memory is major constraint. Flyweight pattern reuses already created similar objects and stores them and creates new object only when no similar object found. So by doing this it reduces number of new objects created and decrease memory usage. Flyweight pattern uses sharing mechanism to support large number of objects efficiently.

Major components of Flyweight pattern –


Flyweight – This is an interface defines the members of flyweight class.
Concrete Flyweight – This is concrete class which implements flyweight interface.
Unshared Concrete Flyweight – This is concrete class which implements flyweight interface and not shared.
Flyweight Factory – This class acts as factory and creates different types of objects as per client request. This class also ensures that it will return shared object if already created.
Client – This is client class and has reference to flyweight interface and request flyweight factory to get shared/unshared objects.

See below example of Flyweight pattern.

Code –
class Program
{
    //types of shape
    public enum ShapeType
    {
        Rectanlge,
        Circle,
        Triangle
    }
    //Flyweight
    public interface IShape
    {
        void Draw(int cordinates);
    }
    //concrete flyweight
    public class Rectangle : IShape
    {
        public void Draw(int size)
        {
            Console.WriteLine("Drawing rectangle of size {0}", size);
        }
    }
    //concrete flyweight
    public class Circle : IShape
    {
        public void Draw(int size)
        {
            Console.WriteLine("Drawing circle of size {0}", size);
        }
    }
    //unshared concrete flyweight
    public class Triangle : IShape
    {
        public void Draw (int size)
        {
            Console.WriteLine("Drawing triangle of size {0}", size);
        }
    }
    //Flyweight factory class
    public class ShapeFactory
    {
        public Dictionary<ShapeType, IShape> myShapes = new Dictionary<ShapeType, IShape>();
        public IShape GetShape(ShapeType shapeType)
        {
            if (myShapes.Keys.Contains(shapeType))
            {
                //reusing existing object
                Console.WriteLine("Similar type of object is already exist and reusing the same");
                return myShapes[shapeType];
            }
            else
            {
                //if object is not created yet, create using factory pattern
                switch (shapeType)
                {
                    case ShapeType.Rectanlge:
                        IShape rectangle = new Rectangle();
                        myShapes.Add(ShapeType.Rectanlge, rectangle);
                        break;
                    case ShapeType.Circle:
                        IShape circle = new Circle();
                        myShapes.Add(ShapeType.Circle, circle);
                        break;
                    case ShapeType.Triangle:
                        IShape triangle = new Triangle();
                        return triangle;
                    default:
                        Console.WriteLine("No shape found");
                        break;
                }
                return myShapes[shapeType];
            }
        }

    }

    //Client
    static void Main(string[] args)
    {
        ShapeFactory shapeFactory = new ShapeFactory();
        IShape rectangle = shapeFactory.GetShape(ShapeType.Rectanlge);
        rectangle.Draw(100);
        IShape circle = shapeFactory.GetShape(ShapeType.Circle);
        circle.Draw(50);

        //Shape factory returns already existing objects instead of creating new
        IShape rect_exist = shapeFactory.GetShape(ShapeType.Rectanlge);
        rect_exist.Draw(80);
        IShape circ_exist = shapeFactory.GetShape(ShapeType.Circle);
        circ_exist.Draw(40);

        //triangle object is not shared so new object will be created everytime
        IShape triangle1 = shapeFactory.GetShape(ShapeType.Triangle);
        triangle1.Draw(30);
        IShape triangle2 = shapeFactory.GetShape(ShapeType.Triangle);
        triangle2.Draw(31);

        Console.ReadLine();
    }
}

Output –



As you can see in above example, Flyweight pattern uses flyweight factory to create object and manage them. Flyweight factory creates objects and store them, if object is already created it will return the existing object and if not then it will create new object and return. Flyweight factory also manages unshared objects which will be always created returned and never stored. This way flyweight enforces reusability of existing object and reduce memory usage.

I hope this article helps you to know more about Flyweight Pattern. Please leave your feedback in comments section below.

References –

See Also –


Sunday, August 21, 2016

Facade Pattern


Facade pattern provides simpler way to users to access complex subsystems. Facade pattern falls under structural pattern of GOF (Gang of Four) patterns.

When to use –


Facade pattern can be used when you have to deal with multiple classes having complex and difficult logic. Facade class acts as “wrapper” class and provides easy to understand and simple to use interface to client. Facade object decouples the subsystems from the client. Client doesn’t have information about how subsystems objects are created and its methods are called in Facade class. Facade class provides client a simpler way to access subsystems. Facade pattern can also be used when you need entry point to multiple complex subsystems.

Facade pattern can also be ideal choice when you are dealing with multiple legacy systems and you can’t change code of legacy systems due to code unavailability or multiple systems are impacted by code change.

Major components of Facade Pattern –


Facade – This is a class and acts as wrapper for delegating client request to respective subsystems.
Subsystems – This are subsystem classes which contains functionality that client wants.

There are so many real world example available for Facade pattern but most common example is Reception counter or “May I Help you” counter at any company or bank. So client just need to contact to reception counter and he/she will be redirected to respective department to get his/her work done. See below example of Facade pattern.

Code –
//subsystem-1
public class SavingsAccount
{
    public void OpenNewAccount(string name)
    {
        Console.WriteLine(string.Format("{0}, welcome to savings account department", name));
    }
}
//subsystem-2
public class CreditCard
{
    public void ApplyCreditCard(string name)
    {
        Console.WriteLine(string.Format("{0}, welcome to credit card department.", name));
    }
}
//subsystem-3
public class PersonalLoan
{
    public void GetPersonalLoan(string name)
    {
        Console.WriteLine(string.Format("{0}, welcome to personal loan department", name));
    }
}
//Facade
public class Reception
{
    private string Name;
    private SavingsAccount savingsaccount = new SavingsAccount();
    private CreditCard creditCard = new CreditCard();
    private PersonalLoan personalLoan = new PersonalLoan();
    public Reception(string name)
    {
        Name = name;
    }
    public void GetPersonalLoan()
    {
        personalLoan.GetPersonalLoan(Name);
    }
    public void ApplyForCreditCard()
    {
        creditCard.ApplyCreditCard(Name);
    }
    public void OpenSavingsAccount()
    {
        savingsaccount.OpenNewAccount(Name);
    }
}
//client
class Program
{
    static void Main(string[] args)
    {
        Reception reception = new Reception("Mitesh");
        reception.OpenSavingsAccount();
        reception.ApplyForCreditCard();
        reception.GetPersonalLoan();

        Console.ReadLine();
    }
}

Output –




As you can see in above example, Reception class acts as Facade (wrapper) class which is entry point for client to connect to multiple subsystems for his/her different types of need like opening savings account, get personal loan, apply for credit card etc.

I hope this article helps you to know more about Facade Pattern. Please leave your feedback in comments section below.


References –

See Also –