Showing posts with label Visual Studio 2010 Beta 1. Show all posts
Showing posts with label Visual Studio 2010 Beta 1. Show all posts

Thursday, June 4, 2009

Running Parallel Tasks

.NET 4.0 introduces a more "high level" construct than thread to write parallel program, System.Threading.Tasks.Task. Task is a unit of work which could be assigned on to a CPU core. This is a versatile and comprehensive API. You can wait/join a Task, cancel a Task, continue with another task when a task completes and more. When you need this functionality, you should try this class. Task class has a static property, Factory, of type TaskFactory. This class provides methods to create tasks from different options. The simplest way to create a task is, call the StartNew(Action act) method on Task.Factory, passing an Action delegate.

By calling ContinueWith(Action) on a task, we can specify another task which should be completed after a particular task has completed.
You can wait on a task to complete, by calling wait method on task:

You can cancel a task asynchronously, by calling Cancel() on the task:


You can cancel a task Synchronously, by calling CancelAndWait():

You can run a task synchronously, by calling RunSycnronously():

Monday, June 1, 2009

Parallel.ForEach and Parallel.Invoke

Parallel.ForEach method is the parallel equivalent to "serial" foreach loop. It Iterates on a collection of generic type parameter type TSource. You can pass three different collection types: System.Collections.Generic.IEnumerable, System.Collections.Concurrent.Partitioner and System.Collections.Concurrent.OrderablePartitioner. Partioner classes are abstract and are here to write custom partioning code. This topic is beyond the scope of this post, and leave it for the future.
Here is a quick example of how to use this overload of Parallel.ForEach:

ints is IEnumerable and a is an object from this IEnumerable instance. You can use other Stop and Break semantics by replacing the second parameter with other delegate:
Action. and use the ParallelLoopState.Stop or ParallelLoopState.Break to exit from "loop" at the earliest convenience.
Lastly, lets see what's the Parallel.Invoke method has to offer. It takes a variable number of Action delegates, and executes them in parallel. Here is a quick example:

Task1,Task2,Task3,Task4 are dumb methods whose signature matches the Action delegate's, Just to show an example.

Sunday, May 31, 2009

I would like to close this month with the comparison of Parallel.For and serial for loop. For comparison, I took an INEFFICIENT algorithm to find if a given number is prime. Here is the algorithm:


Here is the serial for loop to find the primes from 2 to 100000:

And here is its output:


Note down the Thread ID, and it took 24511 milliseconds. And here is its equivalent Parallel code:



Here comes the output:

Did you notice that 6 different threads run the code in parallel and it took 18220 milliseconds? The Parallel class uses Task class behind the scenes, to parallelize the loop iterations. And depending upon the number of cores of your CPU, it determines the optimal number of threads and assigns these tasks to the threads.

This program determines prime number in a big range of 100000 numbers. But if you replace the both programs for less numbers, say 5000, or 10000, then the serial for loop will be more efficient. Because, Task objects creation incurs overhead and exceeds the solution time. So, if your problem is small try to avoid parallelize your code.

Wednesday, May 27, 2009

C# 4.0 Consume First

C# 4.0 is coming with a great new feature, Consume First. You can consume any type first and define it after consuming. Lets jump straight into the coding, and see how does it work. Start by creating a Console Application, and type a class name, that is not declared, in the main method. I used the ConsumeFirstClass for this example. The intellisence doesn't show the class:

when you type the assignment operator, =, and new the intellisense starts showing this class:

Remember the class name is underlined because we don't have defined it. Now write an arbitrary method, I wrote ConsumeFirstMethod:

Our class object is showing in the intellisense. And pass in the string parameter, you can pass any thing, the method takes as parameter.
Now place the cursor on the ConsumeFirstClass variable declaration and press Ctrl + . to show the available options:


Select "Generate class for 'ConsumeFirstClass' ". Now visual studio 2010 places a new file named ConsumeFirstClass.cs.

Now go the the method call to ConsumeFirstMethod, press Ctrl + . (dot) and select Generate method stub ...

The class definition looks something like this:

The visual studio 2010 class generator is smart enough that it determined our method signature, it takes a string and returns an int.
Now remove the throw statement and place a return statement:

And here is the output...

Ohhhhhhhhhh......... I think something went wrong. Let me fix it. Here is the fixed output:


That is for now. You can declare any type, enum, struct, class by this method. Yes, You can write a class AtomBomb and define a method Blast using Consume First.

Tuesday, May 26, 2009

C# 4.0 Generics and Variance

Yesterday I blogged about using the variance with delegates. Today I will expand that discussion to the Generics. In C# 3.0, arrays are co-variant, meaning array of a child class is also an array of its base class. e.g.
string[] astr = new string[] {"a", "b", "cde" };
object[] aobj = astr;
There was no support for generic variance.
C# 4.0 introduces covariance and contra variance. And changes the definition of IEnumerable to IEnumerable<out T>. The <out T> specifies that if there is a method which takes Enumerable, then the programmer can also pass the IEnumerable<"Derived class of T">. Consider this code:

PlayAll method takes an IEnumerable and two calls to this method inside main work well even we pass IEnumerable and IEnumerable. Because IEnumerable is covariant, so it is legal to pass any derived types IEnumerable where a base class IEnumerable is required.