Labels

Monday, November 15, 2010

Factory - Creational

1.1     Introduction


  • Factory patterns abstract the object instantiation process. They hide how objects are created and help make the overall system independent of how its objects are created and composed.
  • All OO languages have an idiom (new operator) for object creation. Factory patterns allow us to write methods that create new objects without explicitly using the new operator. This allows us to write methods that can instantiate different objects and that can be extended to instantiate other newly-developed objects, all without  modifying the method's code.

  • There are two factory patters viz. Factory and Abstract Factory Method

·         Factory Approach - Focuses on the use of inheritance to decide the object to be instantiated.
·         Abstract Factory Approach - Focuses on the delegation of the instantiation to another object

2      Factory Method Design Pattern:

2.1     Introduction

The Factory Method pattern is a creational pattern. Like other creational patterns, it deals with the problem of creating objects without specifying the actual class of objects that will be created. The Factory Method is intended to define an interface for clients to use to create an object, but lets subclasses decide which class to instantiate. Factory Methods let a class defer instantiation to subclasses.
               

2.2     Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

2.3     Applicability

Use the Factory Method pattern in any of the following situations:

·         A class can't anticipate the class of objects it must create.
·         A class wants its subclasses to specify the objects it creates.

2.4     Structure


2.1     Participants


Product
Defines the interface for the type of objects the factory method creates
ConcreteProduct
Implements the Product interface
Creator
Declares the Factory Method, which returns an object of type Product
ConcreteCreator
Overrides the factory method to return an instance of a ConcreteProduct



2.2     Collaborations

Creator relies on its subclasses to implement the factory method so that it
returns an instance of the appropriate ConcreteProduct

2.3     Intent

So what exactly does it mean when we say that "the Factory Method Pattern lets subclasses decide which class to instantiate?"

·         It means that Creator class is written without knowing what actual ConcreteProduct class will be instantiated.
·         The ConcreteProduct class which is instantiated, is determined solely by which ConcreteCreator subclass is instantiated and used by the application.
·         It does not mean that somehow the subclass decides at runtime which ConreteProduct class to create.

2.4     Actual Implmentation









class MainApp
  {
    static void Main()
    {
     
      Creator[] creators = new Creator[2];
      creators[0] = new ConcreteCreatorA();
      creators[1] = new ConcreteCreatorB();

      foreach(Creator creator in creators)
      {
        Product product = creator.FactoryMethod();
        Console.WriteLine("Created {0}", product.GetType().Name);
      }
    }
  }


2.5     Few more Implmentation




2.6     Pros

·         Shields clients from concrete classes. i.e Code is made more flexible and reusable by the elimination of instantiation of application-specific classes.
·         If a framework uses the Factory Method pattern, it enables third-party developers to plug-in new Products.
·         Code deals only with the interface of the Product class and can work with any ConcreteProduct class that supports this interface
·         The Creator create method can be coded to return a default Product.

2.7     Consequences

·         Clients might have to subclass the Creator class just to instantiate a particular ConcreteProduct. i.e Coding a new Product means writing two classes - one for the Creator and one for the concrete Creator.
·         Static - inheritance based

2.8     Examples in C#

  1. System.Collections.Ienumerable

The Iterator interface traverses a collection of objects. The interface aims to create a way to access the elements in a collection without exposing the internal structure of the collection. One way to implement this interface would be to have every collection class return an iterator object supporting a specific interface for iterating over collections of that particular type only. However, using this approach, one usually ends up exposing the internal structure of the collection being traversed. The FCL uses a better approach: it uses a factory method to return a polymorphic instance of the appropriate iterator class. All iterators returned by this factory method support a common interface for enumerating over all collection classes without exposing the internal structure of the collection being traversed. This has the added benefit of allowing changes to be made to the collection without requiring a change in the client code.

By specifying a GetEnumerator factory method in the IEnumerable interface and by having all collection classes implement this interface, the framework exposes one interface for obtaining an enumerator for a collection. ArrayList is one such class that implements the IEnumerable interface. ArrayList.GetEnumerator returns an IEnumerator object capable of enumerating over the elements in the ArrayList. Figure 1 shows the class hierarchy where the Iterator interface uses the Factory Method pattern.


Since an iterator must have knowledge of the internal structure of the class over which it iterates, it is best to let every class provide its own iterator. IEnumerable classes provide their own iterators using GetEnumerator. In Figure 1, IEnumerable (the Creator) defines the interface by which an IEnumerator (the Product) is returned to the client. A ConcreteCreator (ArrayList) can then be called to return a ConcreteProduct (ArrayListEnumeratorSimple, a private inner class of ArrayList), which is an IEnumerator object capable of iterating over an ArrayList. Clients are required to refer to the returned object by the interface IEnumerator.

  1. The System.Security.Cryptography Classes

The .NET Framework contains a rich and extensible collection of cryptography classes that you can use within your own programs, right out of the box. Cryptography classes are part of the System.Security.Cryptography namespace. These classes use the Factory Method pattern to decouple the choice of algorithms used from their specific implementations.

SymmetricAlgorithm, AsymmetricAlgorithm, and HashAlgorithm are the three roots of the class-inheritance hierarchy in the cryptography framework. These are abstract classes from which specific implementations of various encryption algorithms are derived. Each of these classes supports a static factory method called Create, which creates a particular instance of the cryptography class based on the type of algorithm requested. For example, the following line will instantiate a SymmetricAlgorithm-derived class called DESCryptoServiceProvider, which is the default implementation of the Data Encryption Standard (DES) algorithm in the .NET Framework.


  // Return an instance of DESCryptoServiceProvider
  SymmetricAlgorithm s = SymmetricAlgorithm.Create("DES");

The mapping between the string arguments and the instantiated classes can be found here.

Like WebRequest.Create, SymmetricAlgorithm.Create is a parameterized factory method; it takes a parameter that identifies the type of object to create, and all objects created are of type SymmetricAlgorithm. The use of a parameterized factory method here is important because it provides opportunities for extending the cryptography framework. For example, by adding a mapping for the RC5 algorithm (which does not currently exist in the .NET Framework SDK) that returns an instance of, say, RC5CryptoServiceProvider, one can add an RC5 implementation to the existing framework, and instantiate it using the following line:


  // Return an instance of RC5CryptoServiceProvider
  SymmetricAlgorithm s = SymmetricAlgorithm.Create("RC5");

  1. ASP.NET HTTP Pipeline

Several instances of the Factory Method pattern can be found in the ASP.NET HTTP pipeline. The ASP.NET HTTP pipeline is a set of classes (in the System.Web namespace) that a web server uses to process an incoming HTTP request and return a response to the client. The pipeline takes care of session management, application pooling, caching, security, etc.

At every point in the pipeline, the objective is to advance the request processing by one step by either identifying the objects that can handle the incoming request, or by forwarding the request to objects capable of handling the request. Factory methods come into play when different types of objects need to be instantiated, based on the type of incoming request.

System.Web.HttpApplicationFactory

The entry point in the pipeline is the HttpRuntime object, which creates an instance of HttpContext for the particular request. HttpRuntime does not try to determine the type of HttpApplication object that will handle the request. Instead, it calls the static factory method HttpApplicationFactory.GetApplicationInstance, passing it the HttpContext instance just created. HttpApplicationFactory is an undocumented class that contains the logic required to determine the HttpApplication object capable of handling an incoming request. GetApplicationInstance uses the HttpContext instance to determine the virtual directory (i.e., application) that this request was sent to. If the virtual directory has been called before, then the HttpApplication object (or a derived ASP.Global_asax object, if Global.asax is defined) is returned from the pool of applications. Otherwise, a new HttpApplication object for that virtual directory is created and returned. Figure 4 shows the class diagram for instantiating an HttpApplication object capable of handling the request.



HttpApplicationFactory.GetApplicationInstance is a parameterized factory method. It takes a parameter that identifies the type of product to create, and all products created are of type HttpApplication.


System.Web.IHttpHandlerFactory

Moving farther along in the pipeline, the HttpApplication instance just created needs the object that can handle the type of resource requested. This object is called a handler. To look up the proper handler, the HttpApplication first determines the factory that can create the handler. It does that by looking up the <httphandlers> section of the machine.config file. If it's not found in machine.config, it looks up the application's web.config file, using the inherited configuration model. The <httpHandlers> section in these config files lists the handlers currently registered for the application. A part of this section is reproduced below.


  <httpHandlers>
    <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
    <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" />
    .....
  </httpHandlers>

This section shows the mapping between the type of resource requested and the class capable of creating a handler for that resource. If an .aspx page is requested, the System.Web.UI.PageHandlerFactory class will be called. Once this class has been located, HttpApplication invokes the IHttpHandlerFactory.GetHandler factory method on the IHttpHandlerFactory interface to retrieve a new instance of the handler class. All such factory classes must implement the IHttpHandlerFactory interface. These factory classes have no behavior except to dynamically manufacture new IHttpHandler objects using the GetHandler method. This method returns an IHttpHandler object, which in this example is the System.Web.UI.Page-derived class created from the .aspx file. For an .aspx file called SamplePage.aspx, the compiled class will be called ASP.SamplePage_aspx, as shown in Figure 5. This class serves as the endpoint for the request, and is responsible for populating the response buffer for that particular request.



IHttpHandlerFactory.GetHandler is a classic example of the Factory Method pattern, where IHttpHandlerFactory (the Creator) decides which IHttpHandlerFactory-derived object to create, PageHandlerFactory (the ConcreteCreator) creates ASP.SamplePage_aspx (the ConcreteProduct), which is returned as an IHttpHandler (the Product) object.

Hope this helps.

Thanks & Regards,
Arun Manglick

Abstract Factory - Creational

1.1     Introduction

The Abstract Factory Method pattern is a creational pattern. Like other creational patterns, it deals with the problem of creating objects without specifying the actual class of objects that will be created.

The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation. Actually, the delegated object frequently uses factory methods to perform  the instantiation!

1.2     Intent

To provide an interface for creating families of related or dependent objects without specifying their concrete classes.

1.3     Applicability

Use the Abstract Factory pattern in any of the following situations:

·         A system should be independent of how its products are created, composed, and represented
·         A class can't anticipate the class of objects it must create
·         A system must use just one of a set of families of products
·         A family of related product objects is designed to be used together, and you need to enforce this constraint

1.4     Motivation

Consider a composite class which must contain the same members but be created differently depending on the application. For example, you could have a document which would be printed differently depending on the printer being used, but would still have to contain the same information. The idea behind abstract factory is that you can pass a class (the factory) to the constructor which has a standard interface. This interface is then used by the constructor, but the methods it uses are implemented differently for each kind of factory.



In the above class diagram, you can see how the Client Class function, CreateProduct, uses the AbstractFactory classes' CreateProduct function to create an object of the AbstractProduct class. Because there is no direct connection between the Client and the ConcreteProduct class, the ConcreteProduct can be any derived class of AbstractProduct.

1.5     Structure


1.6     Participants


AbstractProduct
Declare an interface for the type of product object
ConcreteProduct
Defines a product object to be created by the corresponding concrete factory.

Implements the Product interface
AbstractFactory
Declares an interface for operations that create abstract product objects.
ConcreteFactory
Implements the operations to create concrete product objects
Client
Uses only interfaces declared by AbstractFactory and AbstractProduct classes

1.7     Collaborations

·         Normally a single instance of a ConcreteFactory class is created at runtime. (This is an example of the Singleton Pattern.) This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory.
·         AbstractFactory defers creation of product objects to its ConcreteFactory

1.8     Discussion

A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme. The client does not know (nor care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage.

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (eg. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instantiation of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme. (They would all be fancy or modern objects.) The client would need to know how to handle only the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

In software development, a Factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new derived types to be introduced with no change to the code that uses the base object.

Use of this pattern makes it possible to interchange concrete classes without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, incurs the risk of unnecessary complexity and extra work in the initial writing of code.

1.9     Pros

·         Isolation of concrete classes:

The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces. Product class names are isolated in the implementation of the concrete factory; they do not appear in client code.
·         Exchanging Product Families easily:

The class of a concrete factory appears only once in an application, that is where it's instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the concrete factory. Because an abstract factory creates a complete family of products, the whole product family changes at once.
·          Promoting consistency among products:

When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.

1.10  Consequences

·         Adding a new product means changing factory interface + all concrete factories.

Extending abstract factories to produce new kinds of Products isn't easy. That's because the AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses. But you can overcome this problem by using reflection in .Net Framework and defining CreateProduct method in the AbstractFactory class.

1.11  Example1

This structural code demonstrates the Abstract Factory pattern creating parallel hierarchies of objects. Object creation has been abstracted and there is no need for hard-coded class names in the client code.




using System;

namespace Xpanxion.Structural.AbstractFactory
{
  // MainApp test application

  class MainApp
  {
    public static void Main()
    {
      // Abstract factory #1
      AbstractFactory factory1 = new ConcreteFactory1();
      Client c1 = new Client(factory1);
      c1.Run();

      // Abstract factory #2
      AbstractFactory factory2 = new ConcreteFactory2();
      Client c2 = new Client(factory2);
      c2.Run();

      // Wait for user input
      Console.Read();
    }
  }

  // "AbstractFactory"

  abstract class AbstractFactory
  {
    public abstract AbstractProductA CreateProductA();
    public abstract AbstractProductB CreateProductB();
  }

  // "ConcreteFactory1"

  class ConcreteFactory1 : AbstractFactory
  {
    public override AbstractProductA CreateProductA()
    {
      return new ProductA1();
    }
    public override AbstractProductB CreateProductB()
    {
      return new ProductB1();
    }
  }

  // "ConcreteFactory2"

  class ConcreteFactory2 : AbstractFactory
  {
    public override AbstractProductA CreateProductA()
    {
      return new ProductA2();
    }
    public override AbstractProductB CreateProductB()
    {
      return new ProductB2();
    }
  }

  // "AbstractProductA"

  abstract class AbstractProductA
  {
  }

  // "AbstractProductB"

  abstract class AbstractProductB
  {
    public abstract void Interact(AbstractProductA a);
  }

  // "ProductA1"

  class ProductA1 : AbstractProductA
  {
  }

  // "ProductB1"

  class ProductB1 : AbstractProductB
  {
    public override void Interact(AbstractProductA a)
    {
      Console.WriteLine(this.GetType().Name +
        " interacts with " + a.GetType().Name);
    }
  }

  // "ProductA2"

  class ProductA2 : AbstractProductA
  {
  }

  // "ProductB2"

  class ProductB2 : AbstractProductB
  {
    public override void Interact(AbstractProductA a)
    {
      Console.WriteLine(this.GetType().Name +
        " interacts with " + a.GetType().Name);
    }
  }

  // "Client" - the interaction environment of the products

  class Client
  {
    private AbstractProductA AbstractProductA;
    private AbstractProductB AbstractProductB;

    // Constructor
    public Client(AbstractFactory factory)
    {
      AbstractProductB = factory.CreateProductB();
      AbstractProductA = factory.CreateProductA();
    }

    public void Run()
    {
      AbstractProductB.Interact(AbstractProductA);
    }
  }
}



1.12  Example2

This real-world code demonstrates the creation of different animal worlds for a computer game using different factories. Although the animals created by the Continent factories are different, the interactions among the animals remain the same.




using System;

namespace Xpanxion.Structural.AbstractFactory
{
  // MainApp test application

    class MainApp
    {
        public static void Main()
        {
            // Create and run the Africa animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld world = new AnimalWorld(africa);
            world.RunFoodChain();

            // Create and run the America animal world
            ContinentFactory america = new AmericaFactory();
            world = new AnimalWorld(america);
            world.RunFoodChain();

            // Wait for user input
            Console.Read();
        }
    }

    // "AbstractFactory"

    abstract class ContinentFactory
    {
        public abstract Herbivore CreateHerbivore();
        public abstract Carnivore CreateCarnivore();
    }

    // "ConcreteFactory1"

    class AfricaFactory : ContinentFactory
    {
        public override Herbivore CreateHerbivore()
        {
            return new Wildebeest();
        }
        public override Carnivore CreateCarnivore()
        {
            return new Lion();
        }
    }

    // "ConcreteFactory2"

    class AmericaFactory : ContinentFactory
    {
        public override Herbivore CreateHerbivore()
        {
            return new Bison();
        }
        public override Carnivore CreateCarnivore()
        {
            return new Wolf();
        }
    }

    // "AbstractProductA"

    abstract class Herbivore
    {
    }

    // "AbstractProductB"

    abstract class Carnivore
    {
        public abstract void Eat(Herbivore h);
    }

    // "ProductA1"

    class Wildebeest : Herbivore
    {
    }

    // "ProductB1"

    class Lion : Carnivore
    {
        public override void Eat(Herbivore h)
        {
            // Eat Wildebeest
            Console.WriteLine(this.GetType().Name +
              " eats " + h.GetType().Name);
        }
    }

    // "ProductA2"

    class Bison : Herbivore
    {
    }

    // "ProductB2"

    class Wolf : Carnivore
    {
        public override void Eat(Herbivore h)
        {
            // Eat Bison
            Console.WriteLine(this.GetType().Name +
              " eats " + h.GetType().Name);
        }
    }

    // "Client"

    class AnimalWorld
    {
        private Herbivore herbivore;
        private Carnivore carnivore;

        // Constructor
        public AnimalWorld(ContinentFactory factory)
        {
            carnivore = factory.CreateCarnivore();
            herbivore = factory.CreateHerbivore();
        }

        public void RunFoodChain()
        {
            carnivore.Eat(herbivore);
        }
    }
}


1.13  Abstract Factory Design Pattern in ADO.NET 2.0

Abstract Factory is widely used in may application. Here we will see how Abstract Factory is used in ADO.NET 2.0.

ADO.NET 2.0 defines new set of abstract products classes such as DbConnection, DbCommand, DbParameter etc.... In the same time, each product has a concrete product class, like SqlConnection and OralceConnection etc... The XxxConnection classes inherit and implement DbConnection.

Also ADO.NET 2.0 brings new set of abstract factory classes to help us to implement Provider-Independent Data Access Layer. Through the use of DbProviderFactory Class which is an abstract factory class. The abstract factory -DbProviderFactory-declares set of CreateXxx Methods, like, CreateConnection, CreateCommand, CreateParamenter etc...

Each of these methods return a specific abstract product, for example CreateConnection returns DbConnection, CreateCommnad return DbCommand etc...

DbProviderFactory has set of concrete factory classes such as SqlClientFactory, OracleClientFactory etc...These concrete factories implements the CreateXxx methods to return specific products -provider specific classes.

Now have a look at the following UML Class Diagram and compare it with the Abstract Factory structure diagram:



Abstract Factory Participants:
·         AbstractFactory  (DbProviderFactory):
Role: Declares an interface for operations that create abstract product objects.
·         ConcreteFactory (SqlClientFactory, OracleClientFactory, OleDbFactory, OdbcFactory, Other Third-Party Factory):
Role: Implements the operations declared in the AbstractFactory to create concrete product objects.
·         AbstractProduct (DbConnection, DbCommand, DbParameter etc...):
Role: Declares an interface for a type of product object.
·         ConcreteProduct -Product- (SqlConnection, OracleConnection, XxxConnection, SqlCommand, XxxCommand...):
Role: Defines a product object to be created by the corresponding concrete factory and implements the AbstractProduct interface.
·         Client:
Role: Uses only interfaces declared by AbstractFactory and AbstractProduct classes.






using System;

namespace Xpanxion.Structural.AbstractFactory
{ 
  class MainApp
  {
    public static void Main()
    {
      DBProviderFactory sqlFactory = new SqlClientFactory();
      Client c1 = new Client(sqlFactory);
      c1.Run();


      DBProviderFactory oracleFactory = new OracleClientFactory();
      Client c2 = new Client(oracleFactory);
      c2.Run();
    }
  }


  class Client
  {
    private DbConnection dbConnection;
    private DbCommand dbCommand;

    // Constructor
    public Client(DBProviderFactory factory)
    {
      dbConnection = factory.CreateConnection();
      dbCommand = factory.CreateCommand();
    }   
  }
}


Hope this helps.

Thanks & Regards,
Arun Manglick

Thursday, November 11, 2010

Int. TryParse

This one is for me. Sometime it become hard to remember J

 

int checkZero1 = 0;

int checkZero2 = 0;

long checkZero3 = 0;

 

string number1 = "1234567891"; // Allows Max 10 characters

string number2 = "1234567891"; // Allows Max 10 characters // Same as int

string number3 = "1234567891234567891"; // Allows Max 19 characters

 

int.TryParse(number1, out checkZero1);

Int32.TryParse(number2, out checkZero2);

Int64.TryParse(number3, out checkZero3);

 

MessageBox.Show(checkZero1.ToString());

MessageBox.Show(checkZero2.ToString());

MessageBox.Show(checkZero3.ToString());

 

 

Thanks & Regards,

Arun Manglick

 

 

 

 

 

 

 

 

 

 

Wednesday, October 13, 2010

Silverlight Threading

Threading in Silverlight is no more new than the regular Threading works.
However there are two new things to know here.

·         DispatcherTimer
·         BackgroundWorker

DispatcherTimer

Let’s understand the quick need of Dispatcher by below example.

Much like .NET client applications (e.g. WPF & WinForms applications), Silverlight supports a Single-Threaded Apartment Model. In this model, a single thread runs your entire application and owns all the objects that represent user-interface elements. The thread that creates them  owns them, and other threads can’t interact with them directly.
If this rule is violated – as shown in below example, by trying to access a user-interface object from a background thread–you’re certain  to cause an immediate exception, a lock-up, or a subtler problem.


Problem

protected void Unnamed1_Click(object sender, RoutedEventArgs e)
{       
   ThreadStart thst = new ThreadStart(ThreadRole);
   Thread th = new Thread(thst);
   th.Start();      
}


private void ThreadRole()
{
  try
  {
    Thread.Sleep(2000);
    Label1.Text = "Done"; // Does Not Affects
  }
  catch (Exception ex)
  {
    Throw ex;  // Invalid cross-thread access Exception
  }
}



This is where Dispatcher comes in picture. The dispatcher owns the main application thread and thus able to perform the above violated work.


Solution using Dispatacher

private void ThreadRole()
{
  Thread.Sleep(2000);
  this.Dispatcher.BeginInvoke(delegate()
  {
    Label1.Text = "Done";  // Makes Affect
  });
}


The DispatcherTimer doesn’t offer true multithreaded execution. Instead, it triggers a periodic Tick event on the main application thread.
This advantage of having the tick event always executing on the main application thread, side steps synchronization problems and the other headaches. Refer above example.

This event interrupts whatever else is taking place in your application, giving you a chance to perform some work. I.e It halts/locks the main application / user interface.
This behavior on one hand side steps synchronization problems, but on the other hand it also introduces a number of limitations. I.e. This is fine if you need to  frequently perform small amounts of work,  but if it is a time-consuming task, then the user interface locks up until it’s finished. Thus, the DispatcherTimer doesn’t help you make a user interface more responsive.

So the case where time-consuming task is required, you need the real multithreading.

Here are examples of some small amounts of work that can be handled thru DispatcherTimer.
·         For example, it’s a great way to periodically check a web service for new data.  As we know all web service calls are asynchronous and are carried out on a background thread. Thus, we can use the   DispatcherTimer to just launch the web service call asynchronously and come back. This will enable the time-consuming download to take place on a background thread.

The BackgroundWorker (System.ComponentModel.BackgroundWorker)

The BackgroundWorker component, which was first introduced with .NET 2.0 to simplify threading considerations in WinForms applications.
Fortunately, the  BackgroundWorker is equally at home in Silverlight.

The BackgroundWorker component is one of the simplest and safest approaches to multithreading.
This gives you a nearly foolproof way to run a time-consuming task on a separate thread.
Silverlight recommends whenever possible, it’s better to use the straightforward BackgroundWorker component than the lower-level Thread class.
Reason being –

·         It supports event-based model to notify client application about Progress/Cancellation.
·         Secondly, to achieve this event-based model, it uses the dispatcher behind the scenes. Thus abstracts away the marshalling issues with an event-based model. (As discussed above).

The BackgroundWorker’s core events are DoWork, ProgressChanged, and RunWorkerCompleted.


Solution using Dispatacher

private BackgroundWorker backgroundWorker = new BackgroundWorker();
public BackgroundWorkerTest()
{
 InitializeComponent();
 backgroundWorker.WorkerReportsProgress = true;
 backgroundWorker.WorkerSupportsCancellation = true;

 backgroundWorker.DoWork += backgroundWorker_DoWork;
 backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
 backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
}


■ Note
·         BackgroundWorker is perfect if you have a single asynchronous task that runs in the background from start to finish (with optional support for progress reporting and cancellation).
·         If you have something else in mind—for example, an asynchronous task that runs throughout the entire life of your application or an asynchronous task that communicates with your application while it does its work—you must design a customized solution that uses the threading features you’ve already seen.


Hope this helps.

Regards,
Arun Manglick