Basic use-case for Task Unwrap

Introduction

Recently, after months without using .Net/C#, I was enhancing an existing .Net/C# WPF application leveraging the .Net Task Parallel Library (TPL).

But naively applying the JavaScript Promises patterns I had used in the previous months I was bitten by a strange issue which forced me to use the quite exotic Unwrap extension method.

This article describes the issue, explains its cause, provides a fix with Unwrap, and finally provides a more modern version with the C# 5.0 async/await paradigm.
A simple workflow in JavaScript with Promises

Here is a JavaScript implementation of a simple workflow with 3 steps, the second one simulating a delayed processing with setTimeout, using the Promise API:

function doFirstThing() {
	return new Promise(resolve => {
		console.log("First thing done")
		resolve()
	})
}

function doSecondThing() {
	return new Promise(resolve => {
		setTimeout(() => {
			console.log("Second thing done")
			resolve()
		}, 1000)
	})
}

function doThirdThing() {
	return new Promise(resolve => {
		console.log("Third thing done")
		resolve()
	})
}

doFirstThing().then(doSecondThing).then(doThirdThing)

Here is the result once run with Node:

$ node test.js
First thing done
Second thing done
Third thing done

A C# implementation with Tasks

Here is the same workflow implemented with C# using .Net TPL:

using System;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static Task DoFirstThing()
        {
            return Task.Run(() => Console.WriteLine("First thing done"));
        }

        static Task DoSecondThing()
        {
            return Task.Delay(1000).ContinueWith(_ => Console.WriteLine("Second thing done"));
        }

        static Task DoThirdThing()
        {
            return Task.Run(() => Console.WriteLine("Third thing done"));
        }

        static void Main(string[] args)
        {
            DoFirstThing().ContinueWith(_ => DoSecondThing()).ContinueWith(_ => DoThirdThing());

            Console.ReadLine();
        }
    }
}

Note that contrary to JavaScript Promises .Net Tasks are not started/scheduled automatically when created, hence the need to explicitly call Run.

Here is the result:

First thing done
Third thing done
Second thing done

As you see the third step is executed before the second one!

This is because ContinueWith creates a new Task wrapping the provided treatment which only consists in calling DoSecondThing (which itself creates the second task) which returns immediately.

ContinueWith won’t consider the resulting Task, contrary to Promise.then which handles the case of returning a Promise in a specific manner: the Promise returned by then will be resolved only when the underlying Promise will.
Unwrap to the rescue

To retrieve the JavaScript Promises behavior we need to explicitly tell the TPL we want to consider the underlying Task using Unwrap (implemented as an extension method provided by the TaskExtensions class):

DoFirstThing().ContinueWith(_ => DoSecondThing()).Unwrap().ContinueWith(_ => DoThirdThing());

Result is now consistent with JavaScript:

First thing done
Second thing done
Third thing done

A more modern way with await

C# 5.0 adds some syntactic sugar to ease the use of the TPL with the await operator:

await DoFirstThing();
await DoSecondThing();
await DoThirdThing();

await internally calls Unwrap and waits on the underlying Task as expected, and yields the same result.

Note that await can only be used in an async method.

Conclusion

Mapping between languages and frameworks is not always obvious but fortunately nowadays all seem to copycat each other and they end offering the same paradigms and APIs like the async/await duo you use almost in the same manner in both C# and JavaScript.

Check if a password meet the current password policy

In this post I will demonstrate how to verify if a given password meet the current Windows password policy.

We will use the NetValidatePasswordPolicy API for that.

Instead of using C# pinvoke approach, we will call the API through Managed C++ then call the managed C++ DLL with C#. This approach will be much more cleaner and readable.

First, we create our Managed C++ DLL which contains our validation method :

using namespace System;

namespace pwdval
{
    public ref class srPasswordValidator
    {
        public :int ValidatePassword(System::String ^paramPassword)
        {
            pin_ptr<const wchar_t> wchDomain = PtrToStringChars(paramPassword);

            size_t convertedCharsPassword = 0;
            size_t sizeInBytesPassword = ((paramPassword->Length + 1) * 2);
            errno_t errPassword = 0;
            char    *chPassword = (char *)malloc(sizeInBytesPassword);

            errPassword = wcstombs_s(&convertedCharsPassword,
                                    chPassword, sizeInBytesPassword,
                                    wchDomain, sizeInBytesPassword);

            if (errPassword != 0)
                throw gcnew Exception("Password could not be converted");

            // first, find out the required buffer size, in wide characters
            int nPasswordSize = MultiByteToWideChar(CP_ACP, 0, chPassword, -1, NULL, 0);

            LPWSTR wPassword = new WCHAR[nPasswordSize];

            // call again to make the conversion
            MultiByteToWideChar(CP_ACP, 0, chPassword, -1, wPassword, nPasswordSize);

            NET_API_STATUS stat;
            NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG InputArg = {0};
            NET_VALIDATE_OUTPUT_ARG* pOutputArg = NULL;
            wchar_t* wzServer = 0;

            //wchar_t wzPwd = chPassword;
            InputArg.ClearPassword = wPassword;
            InputArg.PasswordMatch = TRUE;
            stat = NetValidatePasswordPolicy(wzServer, NULL, NetValidatePasswordChange, &InputArg, (void**)&pOutputArg);

            NET_API_STATUS intStatus = pOutputArg->ValidationStatus;

            NetValidatePasswordPolicyFree((void**)&pOutputArg);
            delete []wPassword;

            return intStatus;
        }

    };
}

This method returns an integer that we will convert to an Enum

enum enmResult
        {
            // <summary> 2234 - This operation is not allowed on this special group. </summary>
            SpeGroupOp = 2234,
            // <summary> 2235 - This user is not cached in user accounts database session cache. </summary>
            NotInCache = 2235,
            // <summary> 2236 - The user already belongs to this group. </summary>
            UserInGroup = 2236,
            // <summary> 2237 - The user does not belong to this group. </summary>
            UserNotInGroup = 2237,
            // <summary> 2238 - This user account is undefined. </summary>
            AccountUndefined = 2238,
            // <summary> 2239 - This user account has expired. </summary>
            AccountExpired = 2239,
            // <summary> 2240 - The user is not allowed to log on from this workstation. </summary>
            InvalidWorkstation = 2240,
            // <summary> 2241 - The user is not allowed to log on at this time. </summary>
            InvalidLogonHours = 2241,
            // <summary> 2242 - The password of this user has expired. </summary>
            PasswordExpired = 2242,
            // <summary> 2243 - The password of this user cannot change. </summary>
            PasswordCantChange = 2243,
            // <summary> 2244 - This password cannot be used now. </summary>
            PasswordHistConflict = 2244,
            // <summary> 2245 - The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. </summary>
            PasswordTooShort = 2245
        }

You can find the complete enum definition in the sources downloadable at the end of the post.

Here is now hows we use the DLL to validate a password :

        private object pwValidator;

        public PwdVal()
        {
            foreach (string curModule in Directory.GetFiles(ModuleSearchPath, "srPasswordValidator.dll"))
            {
                try
                {
                    Assembly objAssembly = Assembly.LoadFile(curModule);
                    System.Type objType = objAssembly.GetType("pwdval.srPasswordValidator");

                    if ((objType != null))
                    {
                        pwValidator = Activator.CreateInstance(objType);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    pwValidator = null;
                }
            }
        }

        private string ModuleSearchPath
        {
            get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
        }

        public bool ValidatePassword(string paramPassword, ref string paramReason)
        {
            try
            {
                if (pwValidator == null)
                {
                    paramReason = "Could not validate the password - pwValidator is NULL";
                    return false;
                }

                object obj = pwValidator.GetType().GetMethod("ValidatePassword").Invoke(pwValidator, new object[] { paramPassword });

                if (obj == null)
                {
                    paramReason = "Could not validate the password - obj is NULL";
                    return false;
                }

                int val = Int32.Parse(obj.ToString());

                enmResult intResult = (enmResult)val;

                paramReason = intResult.ToString();

                return intResult == enmResult.Success;
            }
            catch (Exception ex)
            {
                paramReason = ex.Message;
                return false;
            }
        }

You can download sources and sample here : http://dl.free.fr/q04LOHSpM

Accessing 64 bit registry from a 32 bit process

As you may know, Windows is virtualizing some parts of the registry under 64 bit.

So if you try to open, for example, this key : “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90”, from a 32 bit C# application running on a 64 bit system, you will be redirected to : “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90”

Why ? Because Windows uses the Wow6432Node registry entry to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32 bit applications that runs on a 64 bit systems.

If you want to explicitly open the 64 bit view of the registry, here is what you have to perform :

You are using VS 2010 and version 4.x of the .NET framework

It’s really simple, all you need to do is, instead of doing :

//Will redirect you to the 32 bit view
RegistryKey sqlsrvKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

do the following :

RegistryKey localMachineX64View = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey sqlsrvKey = localMachineX64View.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

Prior versions of the .NET framework

For the prior versions of the framework, we have to use P/Invoke and call the function RegOpenKeyExW with parameter KEY_WOW64_64KEY

        enum RegWow64Options
        {
            None = 0,
            KEY_WOW64_64KEY = 0x0100,
            KEY_WOW64_32KEY = 0x0200
        }

        enum RegistryRights
        {
            ReadKey = 131097,
            WriteKey = 131078
        }

        /// <summary>
        /// Open a registry key using the Wow64 node instead of the default 32-bit node.
        /// </summary>
        /// <param name="parentKey">Parent key to the key to be opened.</param>
        /// <param name="subKeyName">Name of the key to be opened</param>
        /// <param name="writable">Whether or not this key is writable</param>
        /// <param name="options">32-bit node or 64-bit node</param>
        /// <returns></returns>
        static RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
        {
            //Sanity check
            if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
            {
                return null;
            }

            //Set rights
            int rights = (int)RegistryRights.ReadKey;
            if (writable)
                rights = (int)RegistryRights.WriteKey;

            //Call the native function >.<
            int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);

            //If we errored, return null
            if (result != 0)
            {
                return null;
            }

            //Get the key represented by the pointer returned by RegOpenKeyEx
            RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, false);
            return subKey;
        }

        /// <summary>
        /// Get a pointer to a registry key.
        /// </summary>
        /// <param name="registryKey">Registry key to obtain the pointer of.</param>
        /// <returns>Pointer to the given registry key.</returns>
        static IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
            registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
            //Get the unsafe handle
            IntPtr dangerousHandle = handle.DangerousGetHandle();
            return dangerousHandle;
        }

        /// <summary>
        /// Get a registry key from a pointer.
        /// </summary>
        /// <param name="hKey">Pointer to the registry key</param>
        /// <param name="writable">Whether or not the key is writable.</param>
        /// <param name="ownsHandle">Whether or not we own the handle.</param>
        /// <returns>Registry key pointed to by the given pointer.</returns>
        static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
        {
            //Get the BindingFlags for private contructors
            System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
            //Get the Type for the SafeRegistryHandle
            Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
            //Get the array of types matching the args of the ctor we want
            Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
            privateConstructors, null, safeRegistryHandleCtorTypes, null);
            //Invoke the constructor, getting us a SafeRegistryHandle
            Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });

            //Get the type of a RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the array of types matching the args of the ctor we want
            Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
            privateConstructors, null, registryKeyConstructorTypes, null);
            //Invoke the constructor, getting us a RegistryKey
            RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
            //return the resulting key
            return resultKey;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out int phkResult);

Then we can open our registry key like this :

RegistryKey sqlsrvKey = _openSubKey(Registry.LocalMachine, @"SOFTWARE\Microsoft\Microsoft SQL Server\90", false, RegWow64Options.KEY_WOW64_64KEY);

As you can see, the framework 4 make our life easier 🙂

Serialization & Deserialization of immutable objects

Introduction

When developping our applications we can experience than some reference types have the same behavior than value types. As a matter of fact there is no more references to the copied object . It’s the case for  System.String and System.Nullable<T> which are called immutable object because when affecting new value to these variables a perfect copy is created to set the new value.

Immutable objects have many advantages :

  • No side effect
  • Thread safe
  • Perfect key of map (because of their unchanging Hashcode)
  • A simple copy of the reference represent a implementation of the Cloneable interface

What’s happen when we want to persist these object, by disconnecting them around your system? As a matter of fact, when the object is immutable it is difficult to rebuilt the instance because of its only “getters” and readonly attributes.

Let’s see a possible solution by constructing an immutable class Person.

/// <summary>
    /// Immutable class Person
    /// </summary>
    [DataContract]
    public class Person
    {
        private static readonly DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Person));

        [DataMember]
        private readonly string m_Name;

        public Person(string name)
        {
            this.m_Name = name;
        }

        public String Name
        {
            get
            {
                return this.m_Name;
            }
        }
}

To proceed we’ll be using DataContractSerializer class to perform with DataContract & readonly attribute as DataMember : It serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited (source msdn).

public String ObjectToXML()
{
      using (MemoryStream m = new MemoryStream())
      {
           dcSerializer.WriteObject(m, this);
           m.Position = 0;

           using (StreamReader reader = new StreamReader(m))
           {
                 return reader.ReadToEnd();
            }
      }
}

public static Person XmlToObject(String xmlStream)
{
       using (MemoryStream m = new MemoryStream())
       using (StreamWriter writer = new StreamWriter(m))
       {
            writer.Write(xmlStream);
            writer.Flush();
            m.Position = 0;
            return dcSerializer.ReadObject(m) as Person;
       }
}

And you can use it as following code :

Person p = new Person("Zizou");
String serializedZizou = p.ObjectToXml();
Person ObjectP = Person.XmlToObject(serializedZizou);
String name = ObjectP.Name;

Enjoy! 🙂

How to execute code in another AppDomain that the current one

Introduction

When an assembly has been loaded in an Application Domain, the embeded code can be executed.

This code can be executed in the current Application Domain or in another one, we will see how to proceed by differents way.

For all the following examples we will use a namespace MyNameSpace containing 2 classes :  ObjectRemote & Program.

 // This namespace contains code to be called.
 namespace MyNameSpace
 {
   public class ObjectRemote : System.MarshalByRefObject
   {
     public ObjectRemote ()
     {
       System.Console.WriteLine("Hello, World! (ObjectRemote Constructor)");
     }
   }
   class Program
   {
     static void Main()
     {
       System.Console.WriteLine("Hello, World! (Main method)");
     }
   }
}

I) Loading assembly in the current AppDomain

To reach some code from another application you can load your assembly in the current AppDomain or create a new AppDomain and load your assembly inside.

The following example shows how to load an assembly in the current AppDomain :

static void main()
{
  //Load the assembly into the current AppDomain
 System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@"c:\MyNameSpace.exe")

 //Instanciate ObjectRemote:
 newAssembly.CreateInstance("MyNameSpace.ObjectRemote");
}

II)Loading assembly in another AppDomain

When using this approach, you have to use ExecuteAssembly method of AppDomain class to reach the default entry point or CreateInstanceFrom method to create an instance of the ObjectRemote.

static void main()
{
//Load the assembly into another AppDomain and call the default entry point
System.AppDomain newAppDomain = new System.AppDomain.CreateDomain("");
NewAppDomain .ExecuteAssembly(@"c:\MyNameSpace.exe")

//Create an instance of ObjectRemote
NewAppDomain.CreateInstanceFrom(@" :\MyNameSpace.exe"," MyNameSpace.ObjectRemote");
}

Enjoy 😉

IoC Pattern

Introduction:

IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.

Let’s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.

public class Song
{
  public string GetStyle()
  {
      return "Rock n Roll !";
  }
}

public class LineUp
{
  public string GetFormation()
  {
      return "Trio";
  }
}

public class Singer
{
  Song song;
  LineUp lineUp;

  public Singer()
  {
      song = new Song();
      lineUp = new LineUp();
  }

  public string Sing()
  {
      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
  }
}

here’s the Main method :

Singer singer = new Singer();
Console.WriteLine(singer.Sing());

As result we have : singer sings Rock n Roll ! and it is a Trio
But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!

Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.

public interface ISong
{
  public string GetStyle();
}

public interface ILineUp
{
  public string GetFormation();
}

public class Song : ISong
{
  public string ISong.GetStyle()
  {
      return "Hip Hop !";
  }
}

public class LineUp : ILineUp
{
  public string ILineUp.GetFormation()
  {
      return "Solo";
  }
}

public class Singer
{
  ISong _isong;
  ILineUp _ilineup;

  public string Singer(ISong is, ILineUp il)
  {
      _isong = is;
      _ilineup = il;
  }

  public string Sing()
  {
      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
  }
}

here’s the Main method : Now if we want to here another artist, we just have to
instanciate so many class that we want

//Creating dependencies
Song oldsong = new Song();
LineUp oldlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(oldsong,oldlineup);
Console.WriteLine(singer.Sing());

//Creating dependencies
Song newsong = new Song();
LineUp newlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(newsong,newlineup);
Console.WriteLine(singer.Sing());

Thanks for reading !!

How to provide a Parallel.For loop in C#2.0

Introduction:

As you have seen in this article Parallel.For loop in C#4.0 invokes a given instruction, passing in arguments :

  • an Integer type “from inclusive”
  • an Integer type “to exclusive”
  • a delegate for the action to be done

This is done on multiple threads.
In this article we will see a way to implement a static For method in C#2.0 having the same behavior.

First of all, let’s implementing our delegate which will be passed in parameter of our For static method.

public delegate void DelegateFor(int i);
public delegate void DelegateProcess();

Now the For static method

public class Parallel
{
   public static void For(int from, int to, DelegateFor delFor)
   {
      //step or chunck will be done as 4 by 4
      int step = 4;
      int count = from - step;
      int processCount = Environment.ProcessorCount;

      //Now let's take the next chunk 
      DelegateProcess process = delegate()
      {
         while (true)
         {
            int iter = 0;
            lock (typeof(Parallel))
            {
               count += step;
               cntMem = count;
            }
            for (int i = iter ; i < iter  + step; i++)
            {
              if (i >= to)
                return;
                delFor(i);
            }
         }
      };

     //IAsyncResult array to launch Thread(s)
     IAsyncResult[] asyncResults = new IAsyncResult[processCount];
     for (int i = 0; i < processCount; ++i)
     {
         asyncResults[i] = process.BeginInvoke(null, null);
     }
     //EndInvoke to wait for all threads to be completed
     for (int i = 0; i < threadCount; ++i)
     {
        process.EndInvoke(asyncResults[i]);
     }
  }
}

Don’t forget that a bigger step would perform the process by reducing lock waiting time. In consequence we would increase parallelism which is not a good idea because of the context changing between a thread and another one which consumes resources.

Do the call like this

class Program
{
  public static void Main(string[] args)
  {
     Parallel.For(0, 100, delegate (int i)
     {
        Console.WriteLine(i + " " + TID);
     });

     Console.Read();
   }

   public static string TID
   {
     get
     {
       return "TID = " +     System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
      }
   }
}

Or using lambda exression in C#3.0 😉

public static void Main(string[] args)
{
  Parallel.For(0, 100, (int i) => Console.WriteLine(i + " " + TID));
  Console.Read();
}

Thanks for reading !!

.Net 4.0 : Overview on Parallel class

Introduction:

In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article.
As a matter of fact at the end of this article you’ll find a link redirecting you in one where we explain you how to implement this static method in C# .Net 2.0!!

Loop For in a C# 2.0 bloc code

public static void MethodWithoutParallel()
{
      List<string>lstInForLoop = new List<string>();
      for(int i =0;<20;i++)
      {
            lstInForLoop.Add(i.ToString());
            //simulate a heavy instruction
            Thread.SpinWait(10);
       }
}

Loop Parallel.For in a C#4.0 bloc code

public static void MethodWithParallel()
{
      List<string>lstInParallelLoop = new List<string>();
      Parallel.For(0, 20, (int i) =>
      {
             lstInParallelLoop.Add(i.ToString());
             //simulate a heavy instruction
             Thread.SpinWait(10);
      });
}

Now let’s compare the timing of these two methods

class Program
{
   public static void Main(string[] args)
   {
      DateTime startTime;
      TimeSpan duration;

      startTime = DateTime.Now;
      MethodWithParallel();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithParallel done in {0}", duration.TotalMilliseconds + " ms");

      startTime = DateTime.Now;
      MethodWithoutParallel ();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithoutParallel  done in {0}", duration.TotalMilliseconds + " ms");

      Console.Read();
    }
}

Output

with Thread.SpinWait method

Running in parallel performs processing time by half !!!
There are endeed dependencies on your hardware (according to the number of cores etc…)

However, let’s remove the Thread.SpinWait static method and run our loops again.

Output

without Thread.SpinWait method

The loop for inside MethodWithoutParallel performs better than the Parallel.For loop inside MethodWithParallel. It makes evidence that it must not be systematically used.
First of all, always find out where are the expensive instructions and if they can be perform thanks to a little step (or chunk) in your loop.

Now let’s have a look on how to provide a Parallel.For loop in C#2.0

Enjoy :)!!

The Yield keyword

Introduction:

Yield keyword is used in an iterator block to provide a value to the enumerator object or notice the end of an iteration.

yield return <expression>;
yield break;

It is very important to know that an iterator block is not a block of code which will be executed. It is a block which will be interpreted by compilator to generate some code. There will have a deeper article about iterators.

Let’s have a look on the following code:

public IEnumerable GetInt(IEnumerable<int> integers)
{
     var listInt = new List<int>();
     foreach (int item in integers)
     {
         //Simulate a long operation.
         Thread.Sleep(5000);
         listInt.Add(item);
     }
     return listInt;
}

As you can read it, we simulate a heavy operation with a Thread.Sleep method. A collection is implemented to collect all typed values,at the end, this collection and its content is returned.

So, in this case we will meet Thread.Sleep method as much that the number of iteration in a Test method call!

Now let’s use Yield keyword:

public IEnumerable GetInt(IEnumerable<int> integers)
{
      foreach (int item in integers)
      {
          //Simulate a long operation.
          Thread.Sleep(5000);
           yield return item;
      }
}

As you can read it, we simulate a heavy operation with a Thread.Sleep method but no collection class is implemented.

Here’s how would be the call method:

public void Test()
{
      int[] tabInt = new int[] { 1, 2, 3, 4, 5, 6 };
      foreach (int item in GetInt(tabInt))
      {
          if (item > 4)
          {
              Console.WriteLine(item);
              break;
          }
      }
}

We will not have to wait for the end of the iteration inside iterator of GetInt method. The current value is analysed and transmited to the current object inside the foreach of the call method Test.

When the condition is verified (item>4) we get out of the foreach loop.
In this case we won’t meet Thread.Sleep method as much that the number of iterations! No more waiting for the end of the block code iteration of GetInt method!

Thanks for reading 🙂

How using Delegates & Events instead of Parent Property

Introduction:

In a WinForm application we can use as much encapsulated UserControls as we want. But what would happen if one of these UserControl must communicate with another one?

Here we will have a look on 2 way to give our solution :

  1. Using Parent property of a control
  2. Using delegates and event programming

The 2nd way is much better because more portable, readable and maintainable!

In this exemple a WinForm will contain a usercontrol (UserControl1) which contains another usercontrol (UserControl2). UserControl2 contains a comboBox having a collection of colors. Choosing a color in this comboBox will change the color of the WinForm control.

Using Parent property of a control

public partial class UserControl2 : UserControl
{
    private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
    {
       #region Using Parent class (bad way)
       switch (this.comboBox1.SelectedIndex)
       {
            case 0:
              //1rst Parent is GroupBox
              //2nd Parent is UserControl1
              //3rd Parent is Form
              Parent.Parent.Parent.BackColor = Color.Blue;
            break;
            case 1:
              Parent.Parent.Parent.BackColor = Color.Red;
            break;
        }
       #endregion
}

Using delegates and event programming

Declaration of our delegate, event and method caling the event

public delegate void ColorChanger(Color color);
public partial class UserControl2 : UserControl
{
    public event ColorChanger ColorChangerExecuter;
    public UserControl2()
    {
            InitializeComponent();
    }

    public void OnChangedSelectIndex(Color color)
    {
        if (this.ColorChangerExecuter != null)
            this.ColorChangerExecuter(color);
    }

The other way of implementing comboBox1_SelectedIndexChanged method

private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
{
    #region Using Delegate with Event (better way)
    switch (this.comboBox1.SelectedIndex)
    {
        case 0:
               this.OnChangedSelectIndex(Color.Blue);
               break;
        case 1:
               this.OnChangedSelectIndex(Color.Red);
               break;
    }
    #endregion

And the call in the WinForm class

public partial class Form1 : Form
{
   UserControl2 uc2 = new UserControl2();
   public Form1()
   {
       InitializeComponent();
       uc2 = this.userControl11.userControl2;
       uc2.ColorChangerExecuter+=new
                            ColorChanger(uc2_ColorChangerExecuter);
  }

 private void uc2_ColorChangerExecuter(Color color)
 {
     this.BackColor = color;
 }
}

A listener has been created, and whatever happen to the comboBox, as we have implemented an event for this control, it will be automatically passed to the WinForm container.