Saturday 21 April 2012

Asynchronous methods in C#: Part II


Introduction
In this article we demonstrate how to report progress information and intermediate results from asynchronous method. This article builds on previous article, Asynchronousmethod in C#: Part I.

Using Code
In this article we do following changes in our previous example.

  • ·         Modify Perform method for reporting progress.
  • ·         Implement ProgressChanged event.
  • ·         Define method ReportProgrss that synchronizes Perform method and ProgressChanged event

Perform Method:
Here is a perform method that we define in our previous example.
        private void Perform(string[] files)
        {
            foreach (string file in files)
            {
                //do something......
                Thread.Sleep(100);
            }
        }
Now we modify it such way, that it reports progress of task to client code and processed files.
        private void Perform(string[] files)
        {
            int counter = 0;
            foreach (string file in files)
            {
                //do something......
                Thread.Sleep(100);

                counter++;
                int percentage = (100 * counter) / files.Length;

                ReportProgress(percentage, file);
            }
        }
After processing file, we compute percentage in percentage and paases it as an argument in ReportProgress() method, which is an example of how to pass intermediate result to client code.

ProgressChanged event:

This event raised whenever asynchronous method wants to report progress to client code.

        public event ProgressChangedEventHandler ProgressChanged
        {
            add
            {
                this.progressChangedEventHandler += value;
            }
            remove
            {
                this.progressChangedEventHandler -= value;
            }
        }
        private ProgressChangedEventHandler progressChangedEventHandler;

        protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
        {
            if (progressChangedEventHandler != null)
                progressChangedEventHandler(this, e);
        }

Handling ProgressChanged event in client code:

Register and implement handler of ProgressChanged event.

        t.ProgressChanged += new ProgressChangedEventHandler(task_ProgressChange);

        static void task_ProgressChange(object sender, ProgressChangedEventArgs e)
        {
            System.Diagnostics.Debug.Print("[Task] Progress: {0} %, Current File: {1}", e.ProgressPercentage, e.UserState);
        }

ReportProgress method:

This method calls ProgressChanged event through AsyncOperation object.

        void ReportProgress(int percentProgress, object userState)
        {
            // FIXME: verify the expected behavior
            if (!IsBusy)
                return;

            async.Post(delegate(object o)
            {
                ProgressChangedEventArgs e = o as ProgressChangedEventArgs;
                OnProgressChanged(e);
            },
                new ProgressChangedEventArgs(percentProgress, userState));
        }


In this series
  1.  Asynchronous method in C#: Part - I 
  2. Asynchronous method in C#: Part - II.

Asynchronous method in C# - Part I


Introduction
In this article, we’ll demonstrate how to write asynchronous method. For better understanding first we’ll perform task conventionally and after that we’ll create its Async version.
Objective
To write Asynchronous method.
Using the code
Let first design class say Task and write a Perform() method that iterate loops over some collection.
    class Task
    {
        private void Perform(string[] files)
        {
            foreach (string file in files)
            {
                //do something......
                Thread.Sleep(100);
            }
        }
    }
See above example in which we are iterating loop for array of string. This is convention method which we all normaly write.
Now, let’s try to perform same task asynchronously using delegates. For this we need following member:
  • Perform() method – does actual work.
  • PerformAsync() method – invokes the asynchronous operation.
  • IsBusy property – indicates that asynchronous operation is going on.
  • CompleteTask() method – called when perform method completed operation.
  • TaskCompleted event – notifies of the asynchronous operation completion.

Perform() Method:
This method executes in background and does actual task. In our example it iterates loop over array of string.
        private void Perform(string[] files)
        {
            foreach (string file in files)
            {
                //do something......
                Thread.Sleep(100);
            }
        }

        delegate void TaskEventHandler(string[] files, AsyncOperation async, SendOrPostCallback callback);

PerformAsync() Method:

This method invokes asynchronous operation and returns immediately. If asynchronous operation is running then throw an exception.

        public void PerformAsync(string[] files)
        {
            if (IsBusy)
                throw new InvalidOperationException("The background worker is busy.");

            async = AsyncOperationManager.CreateOperation(this);

            TaskEventHandler handler =
                new TaskEventHandler(ProcessWorker);
            handler.BeginInvoke(files, async, CompleteWorker, null, null);
        }

First it checks for busy status of operation, if it’s so then throw InvalidCastOperationException.
Next an AsyncOperation is created. This object is used by worker thread to invoke client’s event handler on proper thread.
Next TaskEventHandler is registered with proper handler method. Through TaskEventHandler, we can invoke our Task asynchronously.
Now, the asynchronous operation is started in separate thread using handler.BeginInvoker method. BeginInvoke method contains two more parameter along with string array.
  1. A delegate of type SendOrPostCallback to a callback method which called when operation finishes.
  2. A custom object that is stored in the AsyncState property of  an IAsyncResult instance return by BeginInvoke method.

CompleteTask Method:

This method calls when worker invoker has finishes it’s processes.
        void CompleteTask(object state)
        {
            object[] args = (object[])state;
            RunWorkerCompletedEventArgs e =
                args[0] as RunWorkerCompletedEventArgs;
            AsyncOperation async = args[1] as AsyncOperation;

            SendOrPostCallback callback = delegate(object darg)
            {
                OnRunWorkerCompleted(darg as RunWorkerCompletedEventArgs);
            };

            async.PostOperationCompleted(callback, e);

            this.async = null;
        }

First the AsyncOperation object is obtained and at last TaskCompleted event fired through AsyncOperation object

TaskCompleted Event:
This event fired when the asynchronous operation completed.

        public event RunWorkerCompletedEventHandler TaskCompleted
        {
            add
            {
                this.taskCompletedEventHandler += value;
            }
            remove
            {
                this.taskCompletedEventHandler -= value;
            }
        }
        private RunWorkerCompletedEventHandler taskCompletedEventHandler;

        protected virtual void OnTaskCompleted(RunWorkerCompletedEventArgs e)
        {
            if (taskCompletedEventHandler != null)
                taskCompletedEventHandler(this, e);
        }

In this Series
  1. Asynchronous method in C# - Part I
  2. Asynchronous method in C# - Part II

Friday 13 April 2012

Singleton using C#


Inreoduction
This article intended to give brief overview of singleton pattern. Main intent to define single tone pattern is to ensure a class has only one instance and provide global point of access to it. One may think, this is not big deal, we can achieve same thing by declaring static class. Global static class solves one portion of global accessibility, but does nothing to ensure that single instance of a class running at a time. In singleton, responsibility of having single instance at a time should in a class itself not on the user class. User class should free from this responsibility.

User
Logical Model

                                                                                                     
As shown above, Singleton model is straight forward for understand. There is only one singleton instance. Client can access that instance through single well-known access point.

Physical Model

Physical model of singleton is also as simple as logical one. There are many different ways that singleton have implemented over time. Simple UML of GoF singleton is shown below




Using Code

Let’s understand singleton by defining a simple class as below:

    class MySingleton
    {
        private MySingleton() { }

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }
        private static MySingleton singleton = null;
    }

As shown above we’ve defined singleton class MySingleton. We can see here we define constructor as private constructor that means no one can create instance of this class explicitly. Only way for creating instance is static method CreateInstance(). While creating instance it check’s wether instance has been created before, if not then will create new instance else use previous one. Thus our class will handle responsibility of having single instance at a time. It seems good but may cause a problem in multi-threaded environment. If two threads manage to enter in control block at a same time, two instance of member variable could be created. To solve this one may put control block into crtical section to ensure thread safety, but by doing this each call for instance method will be serialized and cause negative impact on performance. To solve this we’ve to make little change in CreateInstance() method.

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }

Technique we used above called “Double Check Lock”. In this technique we didn’t introduce any new declaration or use any new variable, just we tack advantage of critical section here. The double check occurs at the first IF block. If the member variable is null, then the execution enters a critical section block where the member variable is double checked again. Only after passing this last test is the member variable instantiated. The general thinking is that there is no way that two threads can create two instances of the class using this technique. Also, since there is no thread blocking at the first check, most calls to this method would not get the performance hit of having to enter the lock.
Another way to attempt to fix this problem could be using the volatile keyword on the member variable declaration. This should tell the compiler to not reorder the code and forgo optimization. So our final code will be:

    class MySingleton
    {
        private MySingleton() { }

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }
        private static volatile MySingleton singleton = null;
    }

Conclusion

The Singleton design pattern is a very useful mechanism for providing a single point of object access in an object-oriented application. Regardless of the implementation used, the pattern provides a commonly understood concept that can be easily shared among design and development teams. However, as we have discovered, it is also important to note how different these implementations can be and their potential side effects. The .NET Framework goes a long way to help an implementer of a pattern design the type of functionality desired without having to deal with many of the side effects discussed in this article. The validity of the pattern's original intent is proven when implemented properly.

References
To know more about this pattern kindly follow following URLs


Monday 9 April 2012

ABC of C# Iterator Pattern


Introduction
The aim of this alternative tip is to give more relevant information to the beginner as well as why the heck one should bother about iterators at all.
Lets start with that: why to bother what the iterator pattern is? You use the iterator pattern most likely in your every day work maybe without being aware of:
IList<string> names = new List<string>() { "Himanshu", "Hetal", "Viral" };

foreach (string name in names)
{
    Console.Write("Name : {0}", name);
}

The iterator tells the foreach loop in what sequence you get the elements.

Using  Code

A class that can be used in a foreach loop must provide a IEnumerator<T> GetEnumerator() { ... } method. The method name is reserved for that purpose. This function defines in what sequence the elements are returned.

Some classes may also provide the non-generic IEnumerator GetEnumerator() { ... } method. This is from the older days where there were no generics yet, e.g. all non-generic collections like Array, etc. provide only that "old-fashioned" iterator function.

Behind the scenes, the foreach loop

foreach (string name in names) { ... }

translates into:

Explicit Generic Version                                                                               Explicit non-generic version

using (var it = names.GetEnumerator())          var it = names.GetEnumerator()
while (it.MoveNext())                           while (it.MoveNext())
{                                               {
    string name = it.Current;                       string name = (string)it.Current;
    ....                                            ....
}                                               }

the two explicit iterator calls can be combined into one:

var it = names.GetEnumerator()
using (it as IDisposable)
while (it.MoveNext())
{
    string name = it.Current;
    ....
}

So, the core of the C# implementation of the Iterator Pattern is the GetEnumerator() method. What are now these IEnumerator/IEnumerator<T> interfaces?

What’s an iterator?

An iterator provides a means to iterate (i.e. loop) over some items. The sequence of elements is given by the implementations of the IEnumerator/IEnumerator<T> interfaces:

namespace System.Collections
{
    public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }
}
namespace System.Collections.Generic
{
    public interface IEnumerator<out T> : IDisposable, IEnumerator
    {
        T Current { get; }
    }
}

The pattern is basically given by MoveNext() and Current. The semantics is that one has to first call MoveNext() to get to the first element. If MoveNext() returns false, then there is no more element. Current returns the current element. You are not supposed to call Current if the preceeding MoveNext() returned false.
The MoveNext() gives the next element in the sequence of elements - what ever that sequence is, e.g. from first to last, or sorted by some criteria, or random, etc.
You know now how to apply the iterator pattern (e.g. in a foreach loop) and that this is possible for all classes that provide the above mentioned GetEnumerator() method (the iterator).
What is IEnumerable/IEnumerable<> for?
These interfaces are quite simple:
namespace System.Collections
{
    public interface IEnumerable
   {
        IEnumerator GetEnumerator();
   }
}

namespace System.Collections.Generic
{
    public interface IEnumerable<out T> : IEnumerable
   {
        IEnumerator<T> GetEnumerator();
   }
}
So, easy answer: they provide an iterator (one "old-fashioned", one with generics).
A class that implements one of these interfaces provides an iterator implementation. Furthermore, such an instance can be used wherever one of these interface is needed.
 Note: it is not required to implement this interface to have an iterator: one can provide its GetEnumerator() method without implementing this interface. But in such a case, one can not pass the class to a method where IEnumerable<T> is to be passed.
E.g. there is a List<T> constructor that takes an IEnumerable<T> to initialize its content from that iterator.
namespace System.Collections.Generic
{
    public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
    {
        ...
        public List(IEnumerable<T> collection);
        ...
    }
}
If you look now at the LINQ extension methods: many of these base on IEnumerable<T>, thus, extending any iterator class by some new function that often return yet another iterator. E.g.
namespace System.Linq
{
    public static class Enumerable
     {

        ...
        public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source, Func<TSource, TResult> selector);

        ...
        public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source, Func<TSource, bool> predicate);

        ...
    }
}
This is used as:
    List<string> list = ...;
    var query = from s in list where s.Length > 2 select s;
    foreach (string s in query)
    {
       ...
    }
And again, the C# language provides an alterantive way to express this (one could say simpler):
    List<string> list = ...;
    var query = from s in list where s.Length > 2 select s;
     foreach (string s in query)
    {
       ...
    }
This is LINQ - Language Integrated Queries: Extension methods that can be expressed in the form from ... in ... where ... select (to show some of the LINQ keywords). Please note that you can always write a LINQ expression as a chain of extension methods as shown above.
So, now you know the benefits of the IEnumerable<T> interfaces and where and how they are used.