Sunday, August 17, 2014

Asynchronous Programming in C# – Part 2: Tasks


As discussed in the previous article, though Thread pool helps us up to certain extent of reusing and managing the threads, still it lacks the built in mechanism to know when the operation has finished and what did the thread return back.

So to help programmers to concentrate on the job Microsoft has introduced Task, which is an object that represents some work that should be done. Also Task has the capability to let you know if the work is completed and if a operation returns a result, Task returns you a result.

A Task Scheduler is responsible for starting the Task and managing it. By default the Task Scheduler uses threads from the thread pool to execute the Task.

Basic usage of Task is to make your application being responsive all the time. We make the main thread or thread running the UI free from any background time consuming jobs by creating a Task which internally will be using another thread from the Thread pool to complete the operation. But, note that it helps only in making the application responsive or parallelize your work in order to use the multiple processors available in the computer but does not scale the application.

Task is a part of System.Threading.Tasks name space and it has two forms. One which returns a parameter and another that returns nothing or void.
  • Task<T> which returns a value
  • Task which does not return any value
You can create instances of Task object using a new Task(Action) or using Factory class that creates a instance of Task.

Here is the program for a task (Developed using .NET 4.0) that shows
1) Creation of Task objects
2) Task that returns no value and a Task that returns a value:

using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread {0}", Thread.CurrentThread.ManagedThreadId);
            //Create a task using new keyword
            Task t = new Task(() =>
            {
                Console.WriteLine("Task created using instantiation of Task class and passing Action as a parameter");
            });
t.Start();
            //Create a task using Factory
            //Task.Factory gives access to Factory methods to create instances of Task and Task<T>
            Task taskFactory = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Task created using Task.Factory");
            });
            Console.WriteLine("**********************TASK WITH NO RETURN VALUE***********************");
            Console.WriteLine("Before creating a new task that does not return a value");
            Task taskWithNoReturnValue = Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("TASK WITH NO RETURN VALUE RUNNING ON THREAD {0}", Thread.CurrentThread.ManagedThreadId);
                });
            Console.WriteLine("After creating  a task that does not return a value");
            Console.WriteLine("**********************TASK WITH RETURN VALUE***********************");
            Console.WriteLine("Before creating a new task that returns a value");
            Task<int> taskWithReturnValue = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("TASK WITH NO RETURN VALUE RUNNING ON THREAD {0}", Thread.CurrentThread.ManagedThreadId);
                return 6;
            });
            //Console.WriteLine("The return value from the task is {0}", taskWithReturnValue.Result);
            Console.WriteLine("After creating  a task that returns a value");
            Console.Read();
        }
    }
}
Output:
image

new Task(Action action) / Task.Factory.StartNew(Action action) queues the specified work to run on the thread pool and returns a task handle for that work.

Observe from the output of the program that Main Thread Id is 10 and the tasks are running on 12 and 14. Also notice that the messages “Before…” and “after..” are printed first than the operation performed by the Task. This tells that UI thread or Main thread is running in parallel to the Tasks. Also notice that we are not reading the Task return value in the program. We cannot control the flow of Tasks execution as they each run in a parallel mode on a new thread.

Let us see what happens if we read the value 6 from the Task. Uncomment the commented line that reads and displays the Task’s return value. You can get the result of the Task by property “Result”. Check the output now:

image

The main thread has to wait till the Task’s operation is completed and so you find that first, Task return value is displayed and after that “After..” message is displayed. If the Task is not finished, this call will block the current thread.

So, Task.Result will block the thread that is trying to read the result to wait until the task completes its operation and then the next line of code execution takes place.
There is one more method that makes the current thread to wait and this is similar to Thread.Join(). The method is Task.Wait().

Continuation operation to the Task’s operation:
System.Threading.Tasks class has another method called ContinueWith which creates a continuation task that runs another operation to execute as soon as the Task finishes. There are couple of overloads available for the ContinueWith method that you can configure when the continuation operation will run. It works both with the Task and Task<T> in which the prior case it takes Action as a parameter and in the later case the method accepts Func<<Task<T>,T> as a parameter. For example, in the above program if you want to continue with another operation once the Task<int> is finished, you can add the continuation task as below:

Task<int> taskWithReturnValue = Task.Factory.StartNew(() =>
           {
               Console.WriteLine("TASK WITH NO RETURN VALUE RUNNING ON THREAD {0}", Thread.CurrentThread.ManagedThreadId);
               return 6;
           }).ContinueWith((i) => {return i.Result*5;});

In this case, once the Task<int> completes the operation, then it continues with another operation that takes the result of Task<int> and multiplies the result with 5. So, the return value will be 30 instead of 6 as in the above program. Here is the output:

image

You can use the continuation method for different scenarios like:
  • When the Task is cancelled, if a certain operation is to be performed.
  • If you want to perform some operation if a Task is faulted.
  • If you want to perform some operation if a Task is finished its operation.
Here is a sample program to demonstrate the continuation operations:

static void Main(string[] args)
        {
            Task<string> task = Task.Factory.StartNew(() =>
                {
                    return "Hello EveryOne";
                });
            task.ContinueWith((s) =>
                {
                    Console.WriteLine(" I am completed!!!");
                },TaskContinuationOptions.OnlyOnRanToCompletion);
            task.ContinueWith((s) =>
                {
                   Console.WriteLine(" I am cancelled!!!");
                }, TaskContinuationOptions.OnlyOnCanceled);
            task.ContinueWith((s) =>
            {
                Console.WriteLine(" I am faulted!!!");
            }, TaskContinuationOptions.OnlyOnFaulted);
            Console.WriteLine(task.Result);
            Console.Read();
        }

Output:

image

Since in the program, the Task successfully completed its operation, only continuation option when Task is completed is executed. Had the Task got cancelled or faulted then the other operations would have been displayed.

The option OnlyOnFaulted executes only if the antecedent throws an unhandled exception. Change the above program code as below:

class Program
    {
        static void Main(string[] args)
        {
           Task<string> task = Task.Factory.StartNew(() =>
                {
                    throw new AggregateException("This task cannot execute!!!");
                    return "Hello EveryOne";

                });
            task.ContinueWith((s) =>
                {
                    Console.WriteLine(" I am completed!!!");
                },TaskContinuationOptions.OnlyOnRanToCompletion);
            task.ContinueWith((s) =>
                {
                   Console.WriteLine(" I am cancelled!!!");
                }, TaskContinuationOptions.OnlyOnCanceled);
            task.ContinueWith((s) =>
            {
                Console.WriteLine(" I am faulted!!!");
            }, TaskContinuationOptions.OnlyOnFaulted);
           //Console.WriteLine(task.Result);
            Console.Read();
        }

Note that I have commented out the line to display the result as it goes to exception and you cannot display the result. Also observe that in this program antecedent is the task created in the below line:


Task<string> task = Task.Factory.StartNew(() =>
                {
                    throw new AggregateException("This task cannot execute!!!");
                    return "Hello EveryOne";

                });

With ContinueWith is going to take the result of task and then creates a new Task to perform another operation. If an exception occurs in task operation, then it will propagated to the ContinueWith task’s operation and displays the message “I am faulted”.

  task.ContinueWith((s) =>
                  task.ContinueWith((s) =>
            {
                Console.WriteLine(" I am faulted!!!");
            }, TaskContinuationOptions.OnlyOnFaulted); Output:
image

Press continue and you will see the message below:
image

Task Cancellation:

Here is a simple program to demonstrate the task cancellation:

class Program
    {
        /// <summary>
        /// Method that runs time consuming task.
        /// This method accepts CancellationToken as a parameter.
        /// This program loops through 1 to 2000 and before the count reaches 2000
        /// if user hits any of the key then the tokensource is set to cancel and the token
        /// gets the cancellation request and the loop will get break and control returns to the
        /// Main program.
        /// </summary>
        /// <param name="ct"></param>
        static void RunTimeConsumingTask(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                Console.WriteLine("Cancellation request is sent and the operation is still in the execution");
                return;
            }
            for (int i=1;i<=2000;i++)
            {
                Console.WriteLine("Operation code {0} is completed", i);
                Thread.Sleep(1000);
                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine("Cancelled before completing operation code 2000");
                    break;
                }
            }
        }
        static void Main(string[] args)
        {
            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;
            Console.WriteLine("Press enter or any key to cancel");
            Task<string> task = Task.Factory.StartNew(() =>
                {
                    RunTimeConsumingTask(token);
                    return "Hello EveryOne";
                });
            Console.ReadLine();
            tokenSource.Cancel();
            task.Wait();
            Console.Read();
        }
Output:
image

Here when the loop is reached to 4, if any key is hit then the task is cancelled.

Another program to demonstrate the “TaskContinuation.OnlyOnCanceled”:

In the below program task is the instance of Task class that always looks for the CancellationToken. The CancellationToken propagates the notification that operations should be cancelled.  The CancellationTokenSource is used to signal that the Task should cancel itself.
Another statement to note is below:
token.ThrowIfCancellationRequested();

This statement throws System.OperationCanceledException if token has cancellation requested and this lets the outside the Task code to let the program know that task is getting cancelled. The “ContinueWith” is added to display the message when task is cancelled by creating another task and adding TaskContinuation.OnlyOnCanceled.

static void Main(string[] args)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            CancellationToken token = cancellationTokenSource.Token;
            Task task = Task.Factory.StartNew(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        Console.WriteLine("Executing tasks");
                        Thread.Sleep(1000);
                    }
                    token.ThrowIfCancellationRequested();
                }, token).ContinueWith((t) =>
                    {
                        Console.WriteLine("Task is cancelled");
                    }, TaskContinuationOptions.OnlyOnCanceled);
                Console.WriteLine("Press any key to end the task");
                Console.ReadLine();
                cancellationTokenSource.Cancel();
                task.Wait();
            Console.WriteLine("Press enter to end the application");
            Console.ReadLine();
        }
Output:
image
When enter key is pressed the task is cancelled and the message “Task is cancelled” is displayed.

Nested Tasks:
One task can encapsulate another task or a number of tasks. Nested tasks does not necessarily ensure that outer task waits for the inner tasks to complete.
A simple program to demonstrate the nested tasks:
/// <summary>
        /// Program to show dependencies between Parent
        /// and child tasks
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //parent task created with Task.Factory.StartNew
            //This task is the outer task which is going to encapsulate
            //inner tasks or child tasks
            var parent = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Parent Task statement1");
                //Create a TaskFactory. Once you create a TaskFactory instance, you can create as many tasks
                //as needed.
                TaskFactory tf = new TaskFactory(TaskCreationOptions.None, TaskContinuationOptions.ExecuteSynchronously);
                //Create Child1
                tf.StartNew(() =>
                    {
                        Console.WriteLine("Child1 statement1");
                        Thread.Sleep(5000);
                        Console.WriteLine("Child1 statement2");
                    });
                //Create Child2
                tf.StartNew(() =>
                {
                    Console.WriteLine("Child2 statement1");
                    Thread.Sleep(5000);
                    Console.WriteLine("Child2 statement2");
                });
                Console.WriteLine("Parent Task statement2");
            });
            //Here final task is going to wait for parent task
            var finalTask = parent.ContinueWith(parentTask =>
                {
                    Console.WriteLine("Final statement");
                });
            Console.ReadLine();
        }
image

In this program, we have:
1. One task “parent” is encapsulating two child tasks.
2. Then created a task which is going to execute when the parent task is completed.
3. We cannot control the flow of execution here in the case of child tasks. In the output, you can find that parent task statements are executed first then child’s statements are executed. By the time another statement is executed, final task statement is displayed.

If you want parent to wait till the child tasks to complete, System.Threading provides enum TaskContinuationOptions with value “AttachedToParent”. This will bind the child tasks to the parent task which makes the parent task to wait till the child tasks are completed.

image

Now modify the statement in your program as below:

TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

After this code change you will observe that parent task is going to wait for the child tasks to complete.

Check the following output:
image

Now you observe that final task waits till parent task is completed execution and parent task is going to wait till child tasks are completed.

Now if you see the output, you will get a question as I got when I learnt the basics “From the output it seems all the statements in the parent task are displayed first and then child task statements were displayed. Then how can you support your statement that parent task is going to wait for child tasks to complete?

Here is my answer for the question:

Because the output displays statements with “Parent Task…” are displayed first and then followed by statements with “Child…” does not mean parent has completed the execution and is not waiting for the child to complete. Here is the confirmation with the change highlighted to support:

/// <summary>
        /// Program to show dependencies between Parent
        /// and child tasks
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //parent task created with Task.Factory.StartNew
            //This task is the outer task which is going to encapsulate
            //inner tasks or child tasks
            var parent = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Parent Task statement1");
                //Create a TaskFactory. Once you create a TaskFactory instance, you can create as many tasks
                //as needed.
                TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
                //Create Child1
                tf.StartNew(() =>
                    {
                        Console.WriteLine("Child1 statement1");
                        Thread.Sleep(5000);
                        Console.WriteLine("Child1 statement2");
                    }).ContinueWith((t) =>
                    {
                        Console.WriteLine("Child1 task is completed");
                    }, TaskContinuationOptions.OnlyOnRanToCompletion);
                //Create Child2
                tf.StartNew(() =>
                {
                    Console.WriteLine("Child2 statement1");
                    Thread.Sleep(5000);
                    Console.WriteLine("Child2 statement2");
                }).ContinueWith((t) =>
                {
                    Console.WriteLine("Child2 task is completed");
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
                Console.WriteLine("Parent Task statement2");
            }).ContinueWith((t)=>
                {
                    Console.WriteLine("Parent task is completed");
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
            //Here final task is going to wait for parent task
            var finalTask = parent.ContinueWith(parentTask =>
                {
                    Console.WriteLine("Final statement");
                });
            Console.ReadLine();
        }

Now we have added continue tasks once the task has completed the execution with “TaskContinuationOptions.OnlyOnRanToCompletion”. With this addition of confirmation statements, now check the output that confirms that parent task has completed only after child tasks are completed.
image

Additional methods:
- WaitAll() method can be used to wait for all multiple tasks to finish before continuation.
- WhenAll() method can be used to schedule a continuation method after all Tasks have completed.
- WaitAny() method can be used to wait until one of the Tasks is finished.

Hope you like this article. The programs are coded in C# 4.0. In the next article I will touch the same programs rewritten in C# 5.0 and then we will discuss the new features added in C# 5.0.



Sunday, June 29, 2014

Asynchronous Programming in C# – Part 1:Basics of Thread programming


In these series of articles we are going to discuss on the following items:
  • Single Thread programming
  • Multi-Threading programming
  • Synchronous Programming
  • Asynchronous Programming
  • Advantages/Disadvantages of writing programming using Thread class
  • Advantages/Disadvantages of using Task Parallel Library classes
  • Deep dive into Asynchronous Programming using async and await modifiers

This article uses Visual Studio 2013 and .NET 4.5 version and C# programming language in order to explain the concepts. If you have .NET 3.5, you can still use the examples illustrated with System.Threading classes. If you have .NET 4 version, you should be good in using the examples illustrated with System.Threading classes and System.Threading.Tasks classes. If you have latest version of .NET (.NET 4.5+), you can also follow async and await modifiers examples illustrated in addition to the Threading and Tasks classes.

Convention followed in these articles: Since I am going to use mostly console applications to demonstrate the concepts, I would refer the "Foreground thread" as "Main Thread"  for convenience as it will be running in the main method of the program.

 

Windows OS and Threads:

Threads are the basic unit to which an operating system allocates processor time, and more than one thread can be executing code inside that process. You can find more from the MSDN http://msdn.microsoft.com/en-us/library/aa720724(v=vs.71).aspx.

System.Threading is a low level API for starting, stopping and joining threads.

Windows allows each thread to execute for a certain period. After the period ends, the thread is paused and Windows switches to another thread. This is called Context Switching.

There are two types of threads: Foreground Threads or Main Thread or UI thread which keeps application alive and Background Threads or Worker Threads which processes background work or long-time consuming tasks and reports back to the Foreground Threads.



Single Thread Programming -  All the code in your program is going to be executed on a single thread also called as Main thread or UI thread in case of UI programming.

image

  1. When you run your application, Windows operating system creates a Thread and it is given control to execute the entry method “Main”.
  2. All lines of code in the Main method gets executed on this thread.
  3. If there are any method calls, then the control goes to the called method and the code in those methods are still executed on the same thread. In the picture above, the main thread is “Thread1” and the called methods are “Method1() and Method2()”.
  4. Once the method execution is completed, then the control comes back to the Main method.
  5. Once all the code is executed in the Main method, then Thread is no more used.
  6. Then thread will be killed or destroyed by the operation system.

Here the all methods are executed on same thread and in sequential flow.

If your code is supposed to be intended to run in sequential and there are no I/O tasks involved or any heavy computational tasks involved, then this approach works fine. If there are any time consuming tasks are to be executed, then it will block your application and leaves it in an unusable state.

Simple program to demonstrate Single Threading:

using System;
using System.Threading;

namespace ThreadingTest
{
    class Program
    {
        /// <summary>
        /// Entry method
        /// </summary>
        /// <param name="args">Arguments to the method</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);
            ExecuteMethod1();
            Console.WriteLine("Main Method logic-1 executing....");
            ExecuteMethod2();
            Console.WriteLine("Main Method logic-2 executing....");
            Console.WriteLine("All code execution completed");
            Console.ReadLine();
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod1()
        {

            Console.WriteLine("Method name: ExecuteMethod1 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod2()
        {

            Console.WriteLine("Method name: ExecuteMethod2 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }
    }
}

Output:

image

All code is executed on Thread 8. And also observe that all the lines of code are executed in a sequential order.

Multi-Thread Programming – Code in your program is distributed among multiple threads for execution. Here multiple thread may execute code in synchronous manner or asynchronous based on your programming model.

 

 

image

  1. Windows OS creates a Thread (Main thread) to execute the Main method.
  2. Main thread executes the lines of code in the Main method.
  3. Main method creates a new Thread to execute method Method1().
  4. Main thread then executes other lines of code in the Main method.
  5. Main method creates another new Thread to execute method Method2().
  6. Main thread completes its execution and it does not wait for other two threads to complete their code execution.

Simple program to demonstrate Multi-threading:

using System;
using System.Threading;

namespace ThreadingTest
{
    class Program
    {
        /// <summary>
        /// Entry method
        /// </summary>
        /// <param name="args">Arguments to the method</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);

            //Create Thread to execute ExecuteMethod1
            Thread thread1 = new Thread(ExecuteMethod1);
            thread1.Start();

            Console.WriteLine("Main Method logic-1 executing....");

            //Create Thread to execute ExecuteMethod1
            Thread thread2 = new Thread(ExecuteMethod2);
            thread2.Start();

            Console.WriteLine("Main Method logic-2 executing....");
            Console.WriteLine("All code execution completed");
            Console.ReadLine();
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod1()
        {

            Console.WriteLine("Method name: ExecuteMethod1 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod2()
        {

            Console.WriteLine("Method name: ExecuteMethod2 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }
    }
}

Output:

image

Notice that Main method is running on Thread 8, ExecuteMethod1() is running on Thread 9 and ExecuteMethod2() is running on Thread 10. Also observe that Thread 8 is not waiting for Thread 9 and 10 to complete their execution. This is because, all these threads are running in independent fashion and there is no way to communicate for Thread 9 and 10 with Thread 8. This is one of the drawback if you are writing multi-threading code by directly creating Thread objects.

Synchronous Programming – All blocks of code are executed in sequential manner. If you have 4 blocks of code say A, B, C and D then the execution order will be A—>B—>C—>D to complete the execution. Imagine if multiple threads are given the job of executing each block then the other threads must wait for the current thread to complete its task. In this case, UI gets freeze as UI thread will be waiting for other threads to complete their tasks.

image

  1. Windows creates a Thread (Main Thread) to execute Main method.
  2. Main thread executes the lines of code in the Main method.
  3. Main method creates a new thread to execute Method1().
  4. Then Main thread is blocked to wait for the completion of execution of Method1().
  5. Control transfers to the next line of code in the Main method.
  6. Main method again creates another thread to execute method Method2() and waits for the thread to complete its execution.
  7. After the thread has completed its execution, then the control is transferred back to the next line of code and then Main thread completes execution.

Simple example to demonstrate the Multiple threads running in Synchronous manner:

using System;
using System.Threading;

namespace ThreadingTest
{
    class Program
    {
        /// <summary>
        /// Entry method
        /// </summary>
        /// <param name="args">Arguments to the method</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);

            //Create Thread to execute ExecuteMethod1
            Thread thread1 = new Thread(ExecuteMethod1);
            thread1.Start();
            thread1.Join();

            Console.WriteLine("Main Method logic-1 executing....");

            //Create Thread to execute ExecuteMethod1
            Thread thread2 = new Thread(ExecuteMethod2);
            thread2.Start();
            thread2.Join();

            Console.WriteLine("Main Method logic-2 executing....");
            Console.WriteLine("All code execution completed");
            Console.ReadLine();
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod1()
        {

            Console.WriteLine("Method name: ExecuteMethod1 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod2()
        {

            Console.WriteLine("Method name: ExecuteMethod2 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }
    }
}

 

Output:

image

Notice that Main method is running on thread 8. When the thread Thread 9 is created to execute the method ExecuteMethod1(), it blocked the Thread 8 to run and so first the ExecuteMethod1() code is executed. The the control is transferred to the next line of code in Main method. The Thread 10 is created to execute the method ExecuteMethod2() and the Thread 10 blocks the Thread 8. Once it is completed its execution, the the control goes to the next line of code. So, thread 8 has to wait for other threads to complete their execution so that all the code is executed in sequential order though the code is executed on multiple threads.


Asynchronous Programming – Each block of code will be running in parallel and reports to the Main thread or UI thread once they have completed their execution. UI thread or Main thread do not need to wait for all the threads to complete execution. This is especially useful when user wants to perform some other action on UI while some tasks are running behind the scenes.

image

  1. Windows creates a thread (Main Thread) to execute Main method.
  2. Main Thread executes the lines of code in the method Main().
  3. Main method creates a new Thread to execute Method1() and another one for executing method Method2().
  4. Main thread completes its code execution and then waits for the other two threads to complete their execution.

Simple program to demonstrate the Asynchronous programming using multiple threads:

using System;
using System.Threading;

namespace ThreadingTest
{
    class Program
    {
        /// <summary>
        /// Entry method
        /// </summary>
        /// <param name="args">Arguments to the method</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);

            //Create Thread to execute ExecuteMethod1
            Thread thread1 = new Thread(ExecuteMethod1);
            thread1.Start();

            Console.WriteLine("Main Method logic-1 executing....");

            //Create Thread to execute ExecuteMethod1
            Thread thread2 = new Thread(ExecuteMethod2);
            thread2.Start();

            Console.WriteLine("Main Method logic-2 executing....");

            thread1.Join();
            thread2.Join();
            Console.WriteLine("All code execution completed");
            Console.ReadLine();
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod1()
        {

            Console.WriteLine("Method name: ExecuteMethod1 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod2()
        {

            Console.WriteLine("Method name: ExecuteMethod2 and executing on Thread: {0}",
                Thread.CurrentThread.ManagedThreadId);
        }
    }
}

Output:

image

In this program we have added Thread.Join() methods for both the threads 11 and 12 at the end of the Main method before the last Console.WriteLine() method is executed. These two methods blocks the main thread 10 to wait for the completion of their execution and then the control is returned back to the next line of code in Main method.


So, we have discussed single thread and multiple thread programming.  We often encounter situations where we need to run code in different threads in order to complete the tasks in parallel and still make UI available to do other things. Creating few threads programmatically is beneficial but if we create more number of threads it will be a costly affair.


Passing value from a thread to the executing method:


If you want to pass a value to an executing method from a thread, you need to declare the parameter type as “object” in the method and pass the value as a parameter of the start method of the thread. And in the method you need to cast the object to the desired type while using it. In the following example we are passing the loop counter value as a parameter to the method ExecuteMethod() and casting the object to string type while appending in the message text.
 

using System;
using System.Threading;

namespace ThreadingTest
{
    class Program
    {
        /// <summary>
        /// Entry method
        /// </summary>
        /// <param name="args">Arguments to the method</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);

            //Create Thread to execute ExecuteMethod and pass a value
            Thread thread1 = new Thread(ExecuteMethod);
            thread1.Start("I love Microsoft");
            Console.WriteLine("All code execution completed");
            Console.ReadLine();
        }

        /// <summary>
        /// Method to be executed
        /// </summary>
        static void ExecuteMethod(object message)
        {

            Console.WriteLine("Method name: ExecuteMethod1 and executing on Thread: {0} \nand the message is '{1}'",
                Thread.CurrentThread.ManagedThreadId,
                message.ToString());
        }

    }
}


Output:

image 

 

Points to ponder:


A thread is relatively a heavy weight thing. It at least takes some mega bytes of stack space by default. So imagine the cost if we create more number of threads. Definitely it is not advisable. So, create a Thread in your program only if it is necessary.

You can use Thread Pool class provided by .NET Framework to reuse the threads similar to the database connection pool works. So whenever you are using a thread for the execution of part of code, instead of getting the thread killed we can send it back to the pool so that it can be used again. But there is no mechanism where we can know when the operation is finished and what is the return value of the thread. You can achieve the mechanism by using BackgroundWorker class provided by System.ComponentModel where it has capabilities like to report back the progress of the work, completion of the work. But there is no direct way to do this using Thread class.

One more point to note is that if there are few set of operations that do not consume much time out of the whole operations, creation of Thread for executing those operations is a unnecessary burden to the operating system. All these light operations can be handled by a single thread. It is not advisable to programmatically handle these situations in the code through the creation of Threads. Microsoft has been continuously improving the built in classes for Asynchronous operations in each of the new version it is releasing.

In the next article we will discuss on System.Threading.Tasks provided in .NET version 4.0. It is a high level API for concurrent and asynchronous programming.

Tuesday, March 25, 2014

Why is my code not covered by a Unit Test?

In this article, I am going to speak about a simple method that is not covered in code coverage even though the method is called by the parent method. This surprises many programmers at first instance.
A brief history of “yield” keyword in C# language:
As per MSDN, When you use the yield keyword in a statement, you indicate that the method, operator or get accessor in which it appears is an iterator.
“yield” returns one element at a time.
Iterator Pattern:
Added advantage with the “yield” keyword in your code is making you follow a design pattern by implicit. Yes. By using “yield” keyword you are following Iterator Pattern.
Iterator provides a way to access the elements inside an aggregate object.
Now coming to the main topic of why my method is not covered by Unit Test method.
To explain this I am going to create a class library and add two classes: Country.cs and Data.cs.
The class library name is “DataRepository” and the intention of the library is provide the Country names with Ids. To perform that we need to define the type for “Country” and another type that provides the methods to return the Country names and Ids.
Here is the type “Country”:
image

Here is the class for the provider methods: This class has a public method that is exposed to the clients and one private method that actually reads the data and returns the countries to the public method.
image
Now, let us add a test project and a unit test for the “Data” class public method. The intention of the test method is make sure that the public method of the class “Data” does not return null. This is a simple test.
image
Now execute the unit test and make sure that test is passed and then observe the code coverage details. I am using DOTCOVER (trial version) for code coverage. If you observe the overall Code coverage is 33% and the method “GetCountriesCore” was not covered. Try to put a break point and debug the unit test method, but still debugger will not step into the method “GetCountriesCore”.
image
Also because the type “Country” is called by the method “GetCountriesCore”, it is also not covered.
Now back to the question “Why is my code is not covered even though it is invoked?”
The answer lies in the implementation of the method. The method has “yield” keyword which makes the method to be an iterator and your enumerable method will only execute when you actually try to access the members. This is also called “Deferred Execution”. There is an interesting article in MSDN on the deferred execution: http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx
So, now change the unit test method to iterate through the members of the returned type of the method as below:
image
Now run the tests again and if we put a break point, you can step into the private method too. We should see all green now and coverage percentage should be 100%. Also if you observe, the code for class “Country” is now covered and overall coverage is good now.
image
Hope you find this article useful. Happy Coding!!!

Monday, January 6, 2014

How to pass Professional Scrum Developer I?

Professional Scrum Developer I (PSD I) exam is comprised of theory and concepts from SCRUM Development methodologies and so the prerequisite for this exam is that we need to have knowledge of SCRUM along with the development methodologies. This exam is not so easy as the PSM I and you need to have very good development experience.
Here are the things to be taken care of while preparing the exam:
1. Read SCRUM guide available in scrum.org
2. You should understand the TFS if you are a Microsoft Developer and have knowledge about branching and merging in TFS. You should know when/how to merge and branch the source code.
3. You should understand the Test Driven Development concepts and Acceptance Test Driven concepts. It is advisable to have practical knowledge on the same. In case if you have concepts try to implement a simple example to understand the concepts better.
4. You should know the Build Server and how it works.
5. Most of the times the questions are related to your development experience and often needs judgment in selection of answers.
6. Also you should know about Code Coverage and Unit Testing. Also Code Analysis and Code Metrics. If you do not use these very often in your projects, it is advisable to check the same using Visual Studio.
7. Finally take practice exam (Open Assessment) available in scrum.org. But do not assume you will get more questions from the same. Most of the questions are related to real time experience.
If you are new to everything it is advisable to take a preparation session or course before attempting the exam.