<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;Ak4BQ3Y7cCp7ImA9WhNWFkQ.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299</id><updated>2012-12-16T15:02:32.808-08:00</updated><category term="Priority Queue" /><category term="C#" /><category term="Data Structure" /><category term="Custom Control" /><category term="Dictionary" /><category term="Collections" /><category term="Multi Threading" /><category term=".NET Framework" /><category term="WPF" /><category term="Programming" /><category term="Silverlight" /><category term="Multimap" /><title>Koder Hack</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>5</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/KoderHack" /><feedburner:info uri="koderhack" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><entry gd:etag="W/&quot;AkMCRXk6eyp7ImA9WhZWGEo.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299.post-7139878145730584830</id><published>2011-05-19T05:48:00.000-07:00</published><updated>2011-05-20T01:01:04.713-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-20T01:01:04.713-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="WPF" /><category scheme="http://www.blogger.com/atom/ns#" term="Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Custom Control" /><title>WPF/Silverlight Content Ticker/News Ticker Control</title><content type="html">&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;WPF includes the Canvas control that allows you to place elements using exact coordinates. To position an element on the Canvas, you set the attached Canvas.Left and Canvas.Top properties. Canvas.Left sets the number of units between the left edge of your element and the left edge of the Canvas. Canvas.Top sets the number of units between the top of your element and the top of the Canvas. Although the Canvas control has a definite visible area determined by the Height and Width properties of the control, it allows child controls to be virtually placed at any coordinates. We can use this particular feature of Canvas control to achieve the ticking/sliding effect by&amp;nbsp;continuously&amp;nbsp;changing the coordinates of the content.&lt;br /&gt;
&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-fKv-O3b3kWU/TdUQerXXU3I/AAAAAAAAACM/W1LJO5c0oIk/s1600/demo-screenshot.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-fKv-O3b3kWU/TdUQerXXU3I/AAAAAAAAACM/W1LJO5c0oIk/s1600/demo-screenshot.png" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;Demo application screenshot.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;a href="http://koderhack.blogspot.com/2011/05/content-ticker-control-in-wpf.html"&gt;ContentTicker&lt;/a&gt; control derives from WPF ContentControl. The ControlTemplate is defined to place the content in a Canvas control. Also a double animation is defined that is started on loading of the control. The animation target property is set to the attached property (Canvas.Left) of the content.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;    public class ContentTicker : ContentControl
    {
        Storyboard _ContentTickerStoryboard = null;
        Canvas _ContentControl = null;
        ContentPresenter _Content = null;

        static ContentTicker()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ContentTicker), new FrameworkPropertyMetadata(typeof(ContentTicker)));
        }

        public ContentTicker()
        {
            this.Loaded += new RoutedEventHandler(ContentTicker_Loaded);
        }

        ..
    }
&lt;/pre&gt;&lt;br /&gt;
&lt;pre class="xml" name="code"&gt;&lt;controltemplate targettype="{x:Type local:ContentTicker}"&gt;
        &lt;canvas background="{TemplateBinding Background}" height="{TemplateBinding Height}" horizontalalignment="Stretch" verticalalignment="Stretch" width="{TemplateBinding Width}" x:name="PART_ContentControl"&gt;
            &lt;canvas.triggers&gt;
                &lt;eventtrigger routedevent="Canvas.Loaded"&gt;
                    &lt;beginstoryboard&gt;
                        &lt;storyboard storyboard.targetproperty="(Canvas.Left)" x:name="ContentTickerStoryboard"&gt;
                            &lt;doubleanimation repeatbehavior="Forever" storyboard.targetname="PART_Content"&gt;
                        &lt;/doubleanimation&gt;&lt;/storyboard&gt;
                    &lt;/beginstoryboard&gt;
                &lt;/eventtrigger&gt;
            &lt;/canvas.triggers&gt;
            &lt;contentpresenter content="{TemplateBinding ContentControl.Content}" contenttemplate="{TemplateBinding ContentControl.ContentTemplate}" horizontalalignment="{TemplateBinding ContentControl.HorizontalAlignment}" verticalalignment="{TemplateBinding ContentControl.VerticalAlignment}" x:name="PART_Content"&gt;
        &lt;/contentpresenter&gt;&lt;/canvas&gt;
    &lt;/controltemplate&gt;
&lt;/pre&gt;&lt;br /&gt;
The &lt;a href="http://koderhack.blogspot.com/2011/05/content-ticker-control-in-wpf.html"&gt;ContentTicker&lt;/a&gt; control defines two additional dependency properties for defining the rate (speed) of ticking and direction (east or west). The rate is used to calculate the duration of the animation, the time required to complete one cycle of the animation.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;        public double Rate
        {
            get { return (double)GetValue(RateProperty); }
            set { SetValue(RateProperty, value); }
        }

        public static readonly DependencyProperty RateProperty =
            DependencyProperty.Register("Rate", typeof(double), typeof(ContentTicker), new UIPropertyMetadata(60.0));

        public TickerDirection Direction
        {
            get { return (TickerDirection)GetValue(DirectionProperty); }
            set { SetValue(DirectionProperty, value); }
        }

        public static readonly DependencyProperty DirectionProperty =
            DependencyProperty.Register("Direction", typeof(TickerDirection), typeof(ContentTicker), new UIPropertyMetadata(TickerDirection.West));
&lt;/pre&gt;&lt;br /&gt;
The Canvas size is adjusted while loading the control and Content is vertically aligned in the canvas according to the user specified settings. Further the animation parameters are adjusted according to the Width of Canvas and Content controls. The animation is dependent on the Width of the Canvas and the content so the animation details are updated every time the size of these are changed.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;        void UpdateAnimationDetails(double holderLength, double contentLength)
        {
            DoubleAnimation animation = 
                _ContentTickerStoryboard.Children.First() as DoubleAnimation;
            if (animation != null)
            {
                bool start = false;
                if (IsStarted)
                {
                    Stop();
                    start = true;
                }

                double from = 0, to = 0, time = 0;
                switch (Direction)
                {
                    case TickerDirection.West:
                        from = holderLength;
                        to = -1 * contentLength;
                        time = from / Rate;
                        break;
                    case TickerDirection.East:
                        from = -1 * contentLength;
                        to = holderLength;
                        time = to / Rate;
                        break;
                }

                animation.From = from;
                animation.To = to;
                TimeSpan newDuration = TimeSpan.FromSeconds(time);
                animation.Duration = new Duration(newDuration);

                if (start)
                {
                    TimeSpan? oldDuration = null;
                    if (animation.Duration.HasTimeSpan)
                        oldDuration = animation.Duration.TimeSpan;
                    TimeSpan? currentTime = _ContentTickerStoryboard.GetCurrentTime(_ContentControl);
                    int? iteration = _ContentTickerStoryboard.GetCurrentIteration(_ContentControl);
                    TimeSpan? offset = 
                        TimeSpan.FromSeconds(
                        currentTime.HasValue ? 
                        currentTime.Value.TotalSeconds % (oldDuration.HasValue ? oldDuration.Value.TotalSeconds : 1.0) : 
                        0.0);
                    
                    Start();

                    if (offset.HasValue &amp;amp;&amp;amp;
                        offset.Value != TimeSpan.Zero &amp;amp;&amp;amp;
                        offset.Value &amp;lt; newDuration)
                        _ContentTickerStoryboard.SeekAlignedToLastTick(_ContentControl, offset.Value, TimeSeekOrigin.BeginTime);
                }
            }
        }
&lt;/pre&gt;&lt;br /&gt;
The &lt;a href="http://koderhack.blogspot.com/2011/05/content-ticker-control-in-wpf.html"&gt;ContentTicker&lt;/a&gt; control is generic control to slide the content. It can be used as a news ticker, thumbnails slider, RSS feed slider etc., depending on the requirement. The Start/Stop and Pause/Resume methods can be used to dynamically change the behavior of the sliding content. The demo application uses the control as a text ticker and provides the interfaces to change the speed, content and direction at run time.&lt;br /&gt;
&lt;a href="http://koderhack.blogspot.com/" rel="tag" style="display: none;"&gt;CodeProject&lt;/a&gt;&lt;br /&gt;
&lt;a href="https://sites.google.com/site/irfanamd/ContentTickerSrc.zip"&gt;Download Source&lt;/a&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/7139878145730584830/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://koderhack.blogspot.com/2011/05/content-ticker-control-in-wpf.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/7139878145730584830?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/7139878145730584830?v=2" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/2011/05/content-ticker-control-in-wpf.html" title="WPF/Silverlight Content Ticker/News Ticker Control" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-fKv-O3b3kWU/TdUQerXXU3I/AAAAAAAAACM/W1LJO5c0oIk/s72-c/demo-screenshot.png" height="72" width="72" /><thr:total>3</thr:total></entry><entry gd:etag="W/&quot;D04GSH0zfCp7ImA9WhZXFEQ.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299.post-3885212889083349354</id><published>2011-05-04T00:55:00.000-07:00</published><updated>2011-05-04T00:58:49.384-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-04T00:58:49.384-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Converting Colored Image to Grayscale using C#</title><content type="html">&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Grayscale images also known as black-and-white images carry only intensity information and composed exclusively of &amp;nbsp;shades of gray, varying from black at the weakest intensity and white at the strongest. To convert any color to a grayscale representation of its luminance, first one must obtain the values of its red, green, and blue (RGB) primaries in linear intensity encoding, by gamma expansion. Then, add together 30% of the red value, 59% of the green value, and 11% of the blue value (these weights depend on the exact choice of the RGB primaries, but are typical).&lt;br /&gt;
&lt;br /&gt;
In C#, a colored image can be converted to grayscale by drawing an image using a &lt;b&gt;Graphics&lt;/b&gt; object and rendering it with attributes whose color matrix is set to calculate the color intensities of each pixel according to the grayscale distribution mentioned earlier. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public Bitmap ConvertToGrayscale(Bitmap original)
{
    // Create the grayscale ColorMatrix
    ColorMatrix colorMatrix = new ColorMatrix(
        new float[][] 
        {
            new float[] {.3f, .3f, .3f, 0, 0},           // 30% Red
            new float[] {.59f, .59f, .59f, 0, 0},        // 59% Green
            new float[] {.11f, .11f, .11f, 0, 0},        // 11% Blue
            new float[] {0, 0, 0, 1, 0},                 // Alpha scales to 1
            new float[] {0, 0, 0, 0, 1}                  // W is always 1
        });

    ImageAttributes attributes = new ImageAttributes();
    attributes.SetColorMatrix(colorMatrix);

    // Create a blank bitmap the same size as original and draw
    // the source image at it using the grayscale color matrix.    
    using (Graphics g = Graphics.FromImage(new Bitmap(original.Width, original.Height))
    {
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
    }
    return newBitmap;
}
&lt;/pre&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/3885212889083349354/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://koderhack.blogspot.com/2011/05/converting-colored-image-to-grayscale.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/3885212889083349354?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/3885212889083349354?v=2" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/2011/05/converting-colored-image-to-grayscale.html" title="Converting Colored Image to Grayscale using C#" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>0</thr:total></entry><entry gd:etag="W/&quot;CUcNQX88fCp7ImA9WhZXE08.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299.post-719687096110380209</id><published>2011-05-01T02:24:00.000-07:00</published><updated>2011-05-02T00:58:10.174-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-02T00:58:10.174-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Programming" /><category scheme="http://www.blogger.com/atom/ns#" term=".NET Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="Collections" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Data Structure" /><category scheme="http://www.blogger.com/atom/ns#" term="Multi Threading" /><title>Parallel Programming using Microsoft .NET Framework 4.0</title><content type="html">&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;Wikipedia defines &lt;b&gt;Parallel Computing&lt;/b&gt;&amp;nbsp;as a form of computation in which many calculations are carried out simultaneously, operating on the principle that large problems can often be divided into smaller ones, which are then solved concurrently ("in parallel"). In the past concurrency was virtually achieved by time slicing the processor, i.e., OS would rapidly switch between running programs after a fixed interval called &lt;b&gt;time slice&lt;/b&gt;. That would enable the OS to execute multiple programs simultaneously. These days most computers have more than one cores/CPUs that enable multiple threads to execute simultaneously. Using these cores you can parallelize your code to distribute work across multiple processors.&lt;br /&gt;
&lt;br /&gt;
Microsoft has introduced a new set of libraries, diagnostic tools and &amp;nbsp;runtime in .NET Framework 4.0 to enhance support for parallel computing. The main objective of these features is to simplify parallel development, i.e., writing parallel code in a natural idiom without having to work directly with threads. These include Task Parallel Library (TPL), Parallel LINQ, and new data structures.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Task Parallel Library&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Task Parallel Library (TPL) is a set of types and APIs that simplifies adding parallelism and concurrency to the applications. It handles the partitioning of the work, scheduling of the threads on the &lt;b&gt;ThreadPool&lt;/b&gt;, cancellation support, state management and other low level details. TPL introduces the concept of &lt;b&gt;Data Parallelism&lt;/b&gt;, scenarios in which the same operation is performed concurrently on elements in a source collection or array.&amp;nbsp;Parallel.For and Parallel.ForEach methods in the System.Threading.Tasks namespace are used for this purpose. For example, the following statement is used to concurrently process the items in a source collection;&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;Parallel.ForEach(sourceCollection, item =&amp;gt; Process(item));&lt;/pre&gt;Both these methods have several overloads to let you stop or break loop execution, monitor the state of the loop on other threads, maintain thread-local state, finalize thread-local objects, control the degree of concurrency, and so on.&lt;br /&gt;
&lt;br /&gt;
TPL provides other methods and data types to implicitly or explicitly executes tasks concurrently. The Parallel.Invoke method is used to execute any number of arbitrary statements concurrently. The method accepts variable no. of Action delegates as argument and executes these concurrently. The easiest way to create the Action delegates is to use lambda expressions. For example;&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;Parallel.Invoke(() =&amp;gt; DoSomeWork(), () =&amp;gt; DoSomeOtherWork());&lt;/pre&gt;If a greater control over task execution is required, or you need to return a value from the task TPL includes System.Threading.Tasks.Task and System.Threading.Tasks.Task&amp;lt;TResult&amp;gt; classes this purpose. The &lt;b&gt;Task &lt;/b&gt;object handles the infrastructure details and provides methods/properties for controlling its execution and observing its status. For example, the Status property of a Task determines whether a task has started running, ran to completion, was cancelled, or has thrown an exception. The Task object accepts a delegate (named, anonymous or a lambda expression) as argument at initialization time. Calling the method Start on the Task object starts execution of the provided delegate.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;// Create a task and provide a user delegate.
var task = new Task(() =&amp;gt; Console.WriteLine("Hello from task."));

// Start the task.
taskA.Start();&lt;/pre&gt;The Task object contains a static property Factory that returns an object of the TaskFactory class that provides support for creating and scheduling Task objects.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;// Create and start the task in one operation.
var taskA = Task.Factory.StartNew(() =&amp;gt; Console.WriteLine("Hello from taskA."));
&lt;/pre&gt;The Task class provides many other options to control the execution of operations assigned to the task. The Task.ContinueWith method let you specify a task to be started when the antecedent task completes. The user code executed using a Task can create nested detached and child Tasks. The child tasks are created when the TaskCreationOptions.AttachedToParent is specified while creating the Task. In case of child tasks, the parent task implicitly waits for all child tasks to complete.The Task class provides support to explicitly wait for a single or an array of tasks. The Task.Wait method let you wait for a task to complete. The Task.WaitAny and Task.WaitAll methods let you wait for any or all tasks in an array to complete. When a Task throws one or more exceptions, these are wrapped in an AggregateException and is propagated back to the joining thread. Also the Task class supports cooperative cancellation. The Task class takes a cancellation token as argument at initialization and user can issue cancellation request at some later time.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Parallel LINQ&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Parallel LINQ is the parallel implementation of LINQ to objects. PLINQ implements the full set of LINQ standard query operators as extension methods and defines additional operators for parallel operations. PLINQ queries operate on any in-memory IEnumerable/IEnumerable&amp;lt;T&amp;gt; data source and have deferred execution. It partitions the data source into segments, and then executes the query on each segment on separate worker threads in parallel. The System.Linq.ParallelEnumerable exposes PLINQ's functionality and implements all the standard LINQ operators in addition with operators specific to parallel execution.&lt;br /&gt;
&lt;br /&gt;
A query is executed in parallel when user calls the AsParallel extension method. All the subsequent operations &amp;nbsp;are bound to the ParallelEnumerable&amp;nbsp;implementation.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;var source = Enumerable.Range(1, 10000);

// Opt-in to PLINQ with AsParallel
var evenNums = from num in source.AsParallel()
               where Compute(num) &amp;gt; 0
               select num;
&lt;/pre&gt;PLINQ infrastructure analyzes the overall structure of a query at runtime and executes the query in parallel or sequentially based on the analysis. You can use the WithExecutionMode&amp;lt;TSource&amp;gt; and ParallelExecutionMode enumeration to enforce the PLINQ to use the parallel algorithm. Although PLINQ query operators revert to sequential mode automatically when required, for user-defined query operators the AsSequential operator can be used to revert back to sequential mode&lt;br /&gt;
&lt;br /&gt;
In order to preserve the order of the source sequence in the results PLINQ provides the AsOrdered extension method for this purpose. The sequence is still processed in parallel but the results are buffered to maintain the order. This extra maintenance causes an ordered query to be slow compared to the default AsUnordered&amp;lt;TSource&amp;gt; sequence.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;evenNums = from num in numbers.AsParallel().AsOrdered()
           where num % 2 == 0
           select num;
&lt;/pre&gt;PLINQ queries use deferred execution and the operations are not executed until query is enumerated using a foreach. However, foreach itself does not run in parallel and requires the output from all parallel tasks be merged back into the thread on which the loop is running. For faster query execution when order preservation is not required, PLINQ provides the ForAll operator to parallelize processing of the results from query.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;var nums = Enumerable.Range(10, 10000);

var query = from num in nums.AsParallel()
            where num % 10 == 0
            select num;

// Process the results as each thread completes
// and add them to a System.Collections.Concurrent.ConcurrentBag(Of Int)
// which can safely accept concurrent add operations
query.ForAll((e) =&amp;gt; concurrentBag.Add(Compute(e)));
&lt;/pre&gt;PLINQ queries also support cancellation as is supported by Task. The WithCancellation&lt;tsource&gt; operator accepts the cancellation token instance as argument. When the IsCancellationRequested property is set on the token, PLINQ will stop processing on all threads and throw an OperationCancelledException.&lt;br /&gt;
&lt;br /&gt;
PLINQ wraps the exceptions thrown by multiple threads while executing a query into an AggregateException type and marshals the exception back to the calling thread. Only one try-catch block is required on the calling thread.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Data Structures for Parallel Programming&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The .NET Framework 4.0 introduces several new types that are useful in parallel programming including a set of concurrent collection classes, lightweight synchronization primitives, and types for lazy initialization.&lt;br /&gt;
&lt;br /&gt;
The collection types in the System.Collections.Concurrent namespace provide thread-safe add and remove operations that avoid locks wherever possible and use fine-grained locking where locks are necessary. These include BlockingCollection&amp;lt;T&amp;gt;, ConcurrentBag&amp;lt;T&amp;gt;, ConcurrentDictionary&amp;lt;TKey, TValue&amp;gt;, ConcurrentQueue&amp;lt;T&amp;gt;, and ConcurrentStack&amp;lt;T&amp;gt;. Each of these collection types as compared to the types in System.Collections.Generic namespace provides the thread-safety while performing related operations,e.g., multiple threads can add/remove items from a ConcurrentBag.&lt;br /&gt;
&lt;br /&gt;
In addition with concurrent collections, Microsoft has introduced a new set of fine-grained and performance efficient synchronization primitives in the .NET Framework 4.0. Some of the new types have no counterparts in earlier versions of .NET Framework. These types are defined in System.Threading namespace and include Barrier, CountdownEvent, ManualResetEventSlim, SemaphoreSlim, SpinLock and SpinWait.&lt;br /&gt;
&lt;br /&gt;
The .NET Framework 4.0 also includes classes for initializing objects lazily, i.e., the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. The System.Lazy&amp;lt;T&amp;gt;, System.Threading.ThreadLocal&amp;lt;T&amp;gt; and System.Threading.LazyInitializer are the classes used for this purpose.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Conclusion&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The Task Parallel Library and Parallel LINQ uses &lt;b&gt;System.Threading.ThreadPool&lt;/b&gt; for executing the operations concurrently. The thread pool allocates a pool of threads at the start of an application and manages the threads in a very efficient and intelligent manner. Still it has its own limitations which can affect the choice between a dedicated thread instead of a thread from the thread pool. When a foreground thread is required in an application, all the threads allocated in the pool are marked as background threads. Foreground threads have a priority over background threads and a few CPU intensive foreground threads can starve the background threads for their share of the processor which might result in unexpected performance degradation. Therefore one should consider the overall structure and working of the application while making use of TPL and PLINQ.&lt;br /&gt;
&lt;a href="http://koderhack.blogspot.com/" rel="tag" style="display: none;"&gt;CodeProject&lt;/a&gt;&lt;br /&gt;
&lt;/tsource&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/719687096110380209/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://koderhack.blogspot.com/2011/05/microsoft-net-framework-and-parallel.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/719687096110380209?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/719687096110380209?v=2" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/2011/05/microsoft-net-framework-and-parallel.html" title="Parallel Programming using Microsoft .NET Framework 4.0" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>1</thr:total></entry><entry gd:etag="W/&quot;A0cNRXc6eyp7ImA9WhZQGE4.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299.post-2378363482661380404</id><published>2011-04-26T10:14:00.000-07:00</published><updated>2011-04-26T10:31:34.913-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-26T10:31:34.913-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Programming" /><category scheme="http://www.blogger.com/atom/ns#" term="Dictionary" /><category scheme="http://www.blogger.com/atom/ns#" term="Priority Queue" /><category scheme="http://www.blogger.com/atom/ns#" term=".NET Framework" /><category scheme="http://www.blogger.com/atom/ns#" term="Collections" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Multimap" /><category scheme="http://www.blogger.com/atom/ns#" term="Data Structure" /><title>Priority Queue and Multi Value Sorted Dictionary in C#</title><content type="html">&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;
Microsoft .NET Framework contains a rich set of collection types including &lt;b&gt;generic, non-generic &lt;/b&gt;and &lt;b&gt;specialized &lt;/b&gt;and almost every kind of requirement can be handled using these collections. The introduction of &lt;b&gt;concurrent collections&lt;/b&gt; in .NET Framework 4.0 has even closed the gap for writing custom thread safe collections. Concurrent collections provide the thread safety where multiple threads can access the collections concurrently and work on.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;In one of my projects I required to use &lt;b&gt;Priority Queue &lt;/b&gt;where I could sort the items according to a certain priority and retrieve the item with highest priority.&amp;nbsp;Unfortunately .NET Framework does not include a &amp;nbsp;specific collection type that provides this particular functionality. Searching the web I found multiple implementations of the &lt;b&gt;data structure&lt;/b&gt;&amp;nbsp;here on CodeProject and a third party library PowerCollections that included a number of other collection types. Although I could use any of these, I just wanted a wrapper over one of the .NET Framework collections instead.&lt;br /&gt;
&lt;br /&gt;
Microsoft .NET Framework generic collections includes the &lt;a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx"&gt;sorted dictionary&lt;/a&gt; that represents a collection of key/value pairs sorted on the key. A priority queue can be thought of as a sorted dictionary but it includes multiple values for one key whereas sorted dictionary allows only one value per key. So the idea is to implement a multi value sorted dictionary and then wrap that collection to provide the interfaces for manipulating the Queue functionality.&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;&lt;a href="http://koderhack.blogspot.com/2011/04/priority-queue-and-multi-value-sorted.html"&gt;MultiValueSortedDictionary &lt;/a&gt;&lt;/b&gt;is a wrapper over the &lt;b&gt;SortedDictionary&lt;/b&gt; and implements the generic and non-generic versions of &lt;b&gt;IDictionary&lt;/b&gt;, &lt;b&gt;ICollection &lt;/b&gt;and &lt;b&gt;IEnumerable &lt;/b&gt;interfaces as are implemented by SortedDictionary. The class uses SortedDictionary in a composition relationship instead of inheriting to avoid tightly coupling it to the collection type and to encapsulate the multi value handling. The multiple values for a key are saved in a &lt;b&gt;List&lt;/b&gt; collection and added to the dictionary.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public class MultiValueSortedDictionary&amp;lt;TKey, TValue&amp;gt; : 
                IDictionary&amp;lt;TKey, TValue&amp;gt;, ICollection&amp;lt;KeyValuePair&amp;lt;TKey, TValue&amp;gt;&amp;gt;, 
                IEnumerable&amp;lt;KeyValuePair&amp;lt;TKey, TValue&amp;gt;&amp;gt;, 
                IDictionary, ICollection, IEnumerable
    {
        private SortedDictionary&amp;lt;TKey, List&amp;lt;TValue&amp;gt;&amp;gt; _SortedDictionary;
        private int _Count;
        private bool _IsModified;

        ...
        ...
    }
&lt;/pre&gt;The class uses the IComparer implementation provided to sort the keys. In-case none is provided then it uses the default IComparer implementation associated with the key. The class also accepts a generic dictionary list to copy the elements.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public MultiValueSortedDictionary()
        {
            _SortedDictionary = new SortedDictionary&amp;lt;TKey, List&amp;lt;TValue&amp;gt;&amp;gt;();
        }

        public MultiValueSortedDictionary(IComparer&amp;lt;TKey&amp;gt; comparer)
        {
            _SortedDictionary = new SortedDictionary&amp;lt;TKey, List&amp;lt;TValue&amp;gt;&amp;gt;(comparer);
        }

        public MultiValueSortedDictionary(IDictionary&amp;lt;TKey, TValue&amp;gt; dictionary)
            : this()
        {
            if (dictionary == null) throw new ArgumentNullException("dictionary");

            foreach (KeyValuePair&amp;lt;TKey, TValue&amp;gt; pair in dictionary)
                this.Add(pair.Key, pair.Value);
            _IsModified = false;
        }

        public MultiValueSortedDictionary(IDictionary&amp;lt;TKey, TValue&amp;gt; dictionary, IComparer&amp;lt;TKey&amp;gt; comparer)
            : this(comparer)
        {
            if (dictionary == null) throw new ArgumentNullException("dictionary");

            foreach (KeyValuePair&amp;lt;TKey, TValue&amp;gt; pair in dictionary)
                this.Add(pair.Key, pair.Value);
            _IsModified = false;
        }
&lt;/pre&gt;While adding an item to the collection with a specified key and value, it first checks whether the specified key has already an associated list of values and adds the value to the list. Otherwise it creates a new instance of List&amp;lt;T&amp;gt; collection type, add the value to the list and sets it as the value of the provided key in the sorted dictionary.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public void Add(TKey key, TValue value)
        {
            if (key == null) throw new ArgumentNullException("key");
            
            List&amp;lt;TValue&amp;gt; values;

            if (!_SortedDictionary.TryGetValue(key, out values))
            {
                values = new List&amp;lt;TValue&amp;gt;();
                _SortedDictionary[key] = values;
            }

            values.Add(value);
            ++_Count;
            _IsModified = true;
        }
&lt;/pre&gt;The class implements the indexed property to access the values using array like notation and key as index. It returns the first value in the associated list of values for the key when used as getter and adds the value at the end of list of values associated with the provided key when used as setter.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public TValue this[TKey key]
        {
            get
            {
                if (key == null) throw new ArgumentNullException("key");

                List&amp;lt;TValue&amp;gt; values;
                if (!_SortedDictionary.TryGetValue(key, out values))
                    throw new KeyNotFoundException();
                TValue value = default(TValue);
                if (values != null)
                    value = values[0];
                return value;
            }
            set
            {
                if (key == null) throw new ArgumentNullException("key");

                Add(key, value);
            }
        }
&lt;/pre&gt;The class also implements two methods to remove a key and its associated values from the dictionary or a specific value associated with a key. The method to remove all the associated values of a key accepts the key as parameter and removes the associated list. The method to remove a key/value pair retrieves the list of values associated with the key and deletes the first instance of the value from the list. If the list contains no further values then the key is also removed from the dictionary.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public bool Remove(TKey key)
        {
            if (key == null) throw new ArgumentNullException();

            bool removed = false;
            List&amp;lt;TValue&amp;gt; values;
            if (_SortedDictionary.TryGetValue(key, out values) &amp;amp;&amp;amp;
                _SortedDictionary.Remove(key))
            {
                _Count -= values.Count;
                _IsModified = removed = true;
            }
            return removed;
        }

        public bool Remove(KeyValuePair&amp;lt;TKey, TValue&amp;gt; item)
        {
            if (item.Key == null ||
                item.Key == null)
                throw new ArgumentException();

            bool removed = false;
            List&amp;lt;TValue&amp;gt; values;
            if (_SortedDictionary.TryGetValue(item.Key, out values) &amp;amp;&amp;amp;
                values.Remove(item.Value))
            {
                --_Count;
                if (values.Count == 0)
                    _SortedDictionary.Remove(item.Key);
                removed = true;
                _IsModified = true;
            }
            return removed;
        }
&lt;/pre&gt;Similarly it provides interfaces to safely retrieve a single value or the list of values associated with a key. The two overloads of TryGetValue method are used for this purpose.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public bool TryGetValue(TKey key, out TValue value)
        {
            if (key == null) throw new ArgumentNullException();

            value = default(TValue);
            bool found = false;
            List&amp;lt;TValue&amp;gt; values;
            if (_SortedDictionary.TryGetValue(key, out values))
            {
                value = values[0];
                found = true;
            }
            return found;
        }

        public bool TryGetValue(TKey key, out IEnumerable&amp;lt;TValue&amp;gt; values)
        {
            if (key == null) throw new ArgumentNullException();

            values = null;
            bool found = false;
            List&amp;lt;TValue&amp;gt; valuesList;
            if (_SortedDictionary.TryGetValue(key, out valuesList))
            {
                values = valuesList;
                found = true;
            }
            return found;
        }
&lt;/pre&gt;Further the class defines an inner structure that implements the enumeration interfaces. The enumerator is basically a wrapper over the SortedDictionary and the List enumerators. The MoveNext method iterates recursively over both the enumerators to retrieve the next available key/value pair.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public struct Enumerator : 
            IEnumerator&amp;lt;KeyValuePair&amp;lt;TKey, TValue&amp;gt;&amp;gt;, IDisposable, IDictionaryEnumerator, IEnumerator
        {
            private readonly KeyValuePair&amp;lt;TKey, TValue&amp;gt; DefaultCurrent;
            private MultiValueSortedDictionary&amp;lt;TKey, TValue&amp;gt; _Dictionary;
            private IEnumerator&amp;lt;KeyValuePair&amp;lt;TKey, List&amp;lt;TValue&amp;gt;&amp;gt;&amp;gt; _Enumerator1;
            private IEnumerator&amp;lt;TValue&amp;gt; _Enumerator2;
            private KeyValuePair&amp;lt;TKey, TValue&amp;gt; _Current;

            public bool MoveNext()
            {
                //if (_Disposed)
                //    throw new InvalidOperationException("The enumerator has already been disposed.");

                if (_Dictionary._IsModified)
                    throw new InvalidOperationException("The collection was modified after the enumerator was created.");

                if (!_Valid) return false;
                TKey key = default(TKey);
                TValue value = default(TValue);
                if (_Enumerator2 == null)
                {
                    if (_Enumerator1.MoveNext())
                    {
                        if (_Enumerator1.Current.Value != null)
                            _Enumerator2 = _Enumerator1.Current.Value.GetEnumerator();
                    }
                    else
                        _Valid = false;
                }

                if (!_Valid) return false;

                key = _Enumerator1.Current.Key;
                if (_Enumerator2 != null)
                {
                    if (_Enumerator2.MoveNext())
                        value = _Enumerator2.Current;
                    else
                    {
                        _Enumerator2 = null;
                        return MoveNext();
                    }
                }
                _Current = new KeyValuePair&amp;lt;TKey, TValue&amp;gt;(key, value);
                return true;
            }
        }
&lt;/pre&gt;Once the &lt;a href="http://koderhack.blogspot.com/2011/04/priority-queue-and-multi-value-sorted.html"&gt;MultiValueSortedDictionary&lt;/a&gt;&amp;nbsp;is implemented, it can be used directly as a priority queue or a wrapper class can be defined that provides the interface for using the collection as a queue.&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;public class PriorityQueue&amp;lt;TPriority, TItem&amp;gt; : 
        IDictionary&amp;lt;TPriority, TItem&amp;gt;, IEnumerable&amp;lt;KeyValuePair&amp;lt;TPriority, TItem&amp;gt;&amp;gt;, IDictionary, ICollection, IEnumerable
    {
        MultiValueSortedDictionary&amp;lt;TPriority, TItem&amp;gt; _Dictionary;

        ...
        ...

        public void Enqueue(TPriority priority, TItem item)
        {
            if (priority == null)
                throw new ArgumentNullException("priority");
            _Dictionary.Add(priority, item);
        }

        public TItem Dequeue()
        {
            if (Count == 0)
                throw new InvalidOperationException("The KoderHack.Collections.PriorityQueue&amp;lt;TPriority, TItem&amp;gt; is empty.");

            KeyValuePair&amp;lt;TPriority, TItem&amp;gt; pair = _Dictionary.First();
            _Dictionary.Remove(pair);
            return pair.Value;
        }

        public TItem Peek()
        {
            if (Count == 0)
                throw new InvalidOperationException("The KoderHack.Collections.PriorityQueue&amp;lt;TPriority, TItem&amp;gt; is empty.");

            return _Dictionary.First().Value;
        }
    }
&lt;/pre&gt;That is all implementing a priority queue. I hope this helps!&lt;br /&gt;
&lt;a href="http://koderhack.blogspot.com/2011/04/priority-queue-and-multi-value-sorted.html" rel="tag" style="display: none;"&gt;CodeProject&lt;/a&gt;&lt;br /&gt;
&lt;a href="https://sites.google.com/site/irfanamd/PriorityQueueSrc.zip"&gt;Download Source&lt;/a&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/2378363482661380404/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://koderhack.blogspot.com/2011/04/priority-queue-and-multi-value-sorted.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/2378363482661380404?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/2378363482661380404?v=2" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/2011/04/priority-queue-and-multi-value-sorted.html" title="Priority Queue and Multi Value Sorted Dictionary in C#" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>2</thr:total></entry><entry gd:etag="W/&quot;AkcMQn8yeyp7ImA9WhZQF04.&quot;"><id>tag:blogger.com,1999:blog-2087822490054652299.post-7511951879375586436</id><published>2011-04-21T13:14:00.000-07:00</published><updated>2011-04-25T06:28:03.193-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-25T06:28:03.193-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="WPF" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight" /><title>WPF / Silverlight Countdown Timer and Time Ticker TextBlock</title><content type="html">&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;In one of my applications I had to display a timer for all the items in a &lt;a href="http://msdn.microsoft.com/en-us/library/ms611074(v=VS.90).aspx"&gt;ListView&lt;/a&gt;, i.e., given the last update time of an item I required to display the time elapsed since the update time and update it after every second. In a classic application the solution would have been to add a timer control to the host form and update each elapsed time value at each tick (second) of the timer.&lt;br /&gt;
&lt;br /&gt;
However in WPF/Silverlight &amp;nbsp;we can easily achieve this by creating a custom control inheriting it from the&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/ms617591.aspx"&gt;TextBlock&lt;/a&gt;&amp;nbsp;control. The custom control defines a&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/269ew577.aspx"&gt;TimeSpan&lt;/a&gt;&amp;nbsp;property that holds the time elapsed (or time remaining in case of count down) and binds it to the&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.text.aspx"&gt;TextBlock.Text&lt;/a&gt;&amp;nbsp;property. The TimeSpan is updated every second and thus the Text property displays the updated value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-7ozkCn5znHo/TbKWczKOOiI/AAAAAAAAABw/th_tY1H-a0I/s1600/TimerDemo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="251" src="http://4.bp.blogspot.com/-7ozkCn5znHo/TbKWczKOOiI/AAAAAAAAABw/th_tY1H-a0I/s320/TimerDemo.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;span class="Apple-style-span" style="font-size: xx-small;"&gt;&lt;b&gt;Image:&lt;/b&gt; Countdown Timer and Time Ticker Demo using &lt;a href="http://koderhack.blogspot.com/2011/04/wpf-silverlight-timer-textblock.html"&gt;TimerTextBlock&lt;/a&gt; control.&lt;/span&gt;&lt;/div&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div class="MsoNormal"&gt;&lt;br /&gt;
The control uses&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/library/saba8ksx.aspx"&gt;System.Threading.Timer&lt;/a&gt;&amp;nbsp;object for providing updates. The control initializes a static Timer object with &amp;nbsp;an interval of one second and the &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.timercallback.aspx"&gt;TimerCallback&lt;/a&gt; delegate that is raised after the provided interval. Also the control defines a private static event OnTick that is raised in the callback method.&lt;br /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private static event EventHandler OnTick;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private static Timer _UpdateTimer = new Timer(new TimerCallback(UpdateTimer), null, 1000, 1000);

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private static void UpdateTimer(object state)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;EventHandler onTick = OnTick;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (onTick != null)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;onTick(null, EventArgs.Empty);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
The control subscribes the OnTick event while loading to receive the event and unsubscribes the event while unloading. Also the control binds the TimeSpan property with TextBlock.Text property. Thus the TextBlock.Text property displays the updated TimeSpan value formatted according to the provide TimeFormat.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private void Init()
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Loaded += new RoutedEventHandler(TimerTextBlock_Loaded);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Unloaded += new RoutedEventHandler(TimerTextBlock_Unloaded);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}


&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;void TimerTextBlock_Loaded(object sender, RoutedEventArgs e)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Binding binding = new Binding("TimeSpan");
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;binding.Source = this;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;binding.Mode = BindingMode.OneWay;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;binding.StringFormat = TimeFormat;

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;SetBinding(TextProperty, binding); &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;_UpdateTimeInvoker = new Invoker(UpdateTime);

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;OnTick += new EventHandler(TimerTextBlock_OnTick);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;void TimerTextBlock_Unloaded(object sender, RoutedEventArgs e)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;OnTick -= new EventHandler(TimerTextBlock_OnTick);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}

&lt;/pre&gt;&lt;br /&gt;
The TimeSpan is updated in the OnTick event handler.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="csharp" name="code"&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;void TimerTextBlock_OnTick(object sender, EventArgs e)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;Dispatcher.Invoke(_UpdateTimeInvoker);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private void UpdateTime()
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (IsStarted)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;TimeSpan step = TimeSpan.FromSeconds(1);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (IsCountDown)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (TimeSpan &amp;gt;= TimeSpan.FromSeconds(1))
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;TimeSpan -= step;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (TimeSpan.TotalSeconds &amp;lt;= 0)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;TimeSpan = TimeSpan.Zero;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;IsStarted = false;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;NotifyCountDownComplete();
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;else
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;TimeSpan += step;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}

&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;private void NotifyCountDownComplete()
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;EventHandler handler = OnCountDownComplete;
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if (handler != null)
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;handler(this, EventArgs.Empty);
&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;}

&lt;/pre&gt;&lt;br /&gt;
The control defines additional properties for manipulating and customizing the output. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx"&gt;dependecy property&lt;/a&gt; IsStarted is used to start/stop the timer. The dependency property IsCountDown is used to specify the behavior whether to increase or decrease the TimeSpan at each tick. Also the control defines the dependency property TimeFormat for displaying the time elapsed in a specific format. The TimeSpan class accepts 'c', 'g' and 'G' as &lt;a href="http://msdn.microsoft.com/en-us/library/ee372286.aspx"&gt;standard&lt;/a&gt; format specifiers and formats the output using the common specifier 'c' if none is provided. Also the control defines an event OnCountDownComplete that is raised when the IsCountDown property is set and the TimeSpan value reaches zero.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In order to use the control from &lt;a href="http://msdn.microsoft.com/en-us/library/ms747122.aspx"&gt;XAML&lt;/a&gt;, declare the custom &lt;a href="http://msdn.microsoft.com/en-us/library/ms747086.aspx"&gt;XAML namespace&lt;/a&gt; and map it to the library that defines the control.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="xml" name="code"&gt;xmlns:kh="clr-namespace:KoderHack.WPF.Controls;assembly=KoderHack.WPF.Controls"
&lt;/pre&gt;&lt;br /&gt;
Once the library is available, you can declare the type as follows;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="xml" name="code"&gt;&amp;lt;kh:TimerTextBlock x:Name="ttbCountDown" IsCountDown="True" TimeSpan="00:00:59" IsStarted="True" Width="180" HorizontalAlignment="Center" TextAlignment="Center" FontSize="24" Padding="10" OnCountDownComplete="ttbCountDown_OnCountDownComplete" /&amp;gt;&lt;/pre&gt;&lt;br /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=4183267" rel="tag" style="display: none;"&gt;CodeProject&lt;/a&gt;&lt;br /&gt;
&lt;a href="https://sites.google.com/site/irfanamd/TimerTextBlockDemoSrc.zip"&gt;Download Demo and Source&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://koderhack.blogspot.com/feeds/7511951879375586436/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://koderhack.blogspot.com/2011/04/wpf-silverlight-timer-textblock.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/7511951879375586436?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/2087822490054652299/posts/default/7511951879375586436?v=2" /><link rel="alternate" type="text/html" href="http://koderhack.blogspot.com/2011/04/wpf-silverlight-timer-textblock.html" title="WPF / Silverlight Countdown Timer and Time Ticker TextBlock" /><author><name>Irfan Ahmad</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-7ozkCn5znHo/TbKWczKOOiI/AAAAAAAAABw/th_tY1H-a0I/s72-c/TimerDemo.png" height="72" width="72" /><thr:total>0</thr:total></entry></feed>
