About Me

My photo
Kozyatağı, İstanbul, Türkiye

Friday, April 5, 2013

Thread Local Storage in .NET


In a class, static fields are the most error-prone parts of the application. They need to be handled gracefully since they represent a shared resource.
One and only one instance is created for a static field. That’s why, any change on a static field directly affects all code blocks accessing to it.

Inherently, sometimes classes may need some fields to act like a static variable just for a certain execution context. Actually, here I mean “Executing Thread” while saying “Execution Context”. In other saying, some code may need to protect a static field and create its own copy in its local storage. Thus, any change caused by a thread will not affect the static value that is used by another thread.

Let’s make it clear by a real-life sample:
Suppose, you have many pages in your UI tier. Any changes that is performed on a page by a user, is sent to your Logic tier to be processed. This change is sent to your logic tier as “Message” objects.
( Here we use “Command Pattern” which is one of GoF Design Patterns. Please refer to Command Pattern at: http://www.dofactory.com/Patterns/PatternCommand.aspx)

When the message is received by logic tier, the User that causes the change must be kept in a static field. Because all the remaining functions that will perform and finalize change message will need the User for logging, approval mechanisms, etc.
Similarly, Database handle must be created. Because many codes that run after receiving message are going to need Database connection.
You cannot declare these fields as totally static because it will cause to get incorrect values that is updated by another context. (For example, when the User A and User B perform update in UI tier at the same time, the update that is caused by User A may be logged as if it is updated by User B)

The main necessity here is that; User and Database Handle objects need to be static, but only for the thread that is executing message.
In .NET, there is an extremely convenient and easy-to-use solution to handle this problem. The answer is : ThreadStatic attribute.

C# Code:
class CustomerDetailsUpdateMessage
    {
        [ThreadStatic]
        public static string UserName;

        [ThreadStatic]
        public static IDbHandle DbHandle;

        // Update Inner Details.
    }

Here, when the CustomerDetailsUpdateMessage is received by logic tier, the thread that is executing the message will create its own copy of static UserName and DbHandle fields. So that any other message executing concurrently will not cause any update on the value that accessed by current thread.

Thursday, March 28, 2013

.NET Multithreading and Synchronization


Sometimes we write codes that perform a certain set of functions for many different independent values in identical way.  These set of operations may take remarkably amount of time.
For example, suppose that the program needs to calculate the salaries of all employees and write the results to database. Here is the simplest implementation:

Code:
 void RunSingleThread(List<long> employeeIdList)
        {
            foreach (var employeeId in employeeIdList)
            {
                CalculateSalaryAndWriteToDb(employeeId);
            }
        }


Since every employee is independent from each other, such a task can be performed for many employees in parallel way. Here we can utilize multithreading to shorten the time. We need to implement some steps to achieve it:

n  Decide how many items will run in parallel. As a best practice, this number should be the processor count of the machine.

n Divide the list of items into separated lists. Each of these lists need to have number of parallel items at maximum.

n  In a loop, run all items of executing list in parallel and synchronize them.

n  When all items of executing list completes, skip to next list in the loop.

Here is the C# Code:
        void CalculateSalaryAndWriteToDb(long employeeId, ManualResetEvent mre)
        {
            // Make calculations that takes time.
            // Write To Database.
            mre.Set();
        }

        void RunMultiThread(List<long> employeeIdList)
        {
            int parallelItemCount = Environment.ProcessorCount;
            List<List<long>> groupedItems = GroupItems<long>(employeeIdList, parallelItemCount);
            foreach (List<long> group in groupedItems)
            {
                List<ManualResetEvent> mreList = new List<ManualResetEvent>();
                foreach (var employeeId in group)
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    mreList.Add(mre);
                    ThreadPool.QueueUserWorkItem(o => CalculateSalaryAndWriteToDb(employeeId , mre));
                }
                WaitHandle.WaitAll(mreList.ToArray());
            }
        }

        List<List<T>> GroupItems<T>(List<T> allItems, int groupMaxCount)
        {
            List<List<T>> res = new List<List<T>>();
            int count = 0;
            List<T> temp = new List<T>();
            foreach (var item in allItems)
            {
                count++;
                temp.Add(item);
                if (count % groupMaxCount == 0)
                {
                    res.Add(temp.ToList());
                    temp.Clear();
                }
            }
            if (temp.Any())
            {
                res.Add(temp);
            }
            return res;
        }

Note that, WaitHandle.WaitAll function cannot synchronize more than 64 synchronization objects. System.NotSupportedException is thrown by .NET Framework.

Monday, March 25, 2013

Deep Copying Methods for .NET Objects


When we need to make a copy of an instance of a class, we have two different options that end up with different behaviors.

          Shallow Copy:
     Creates a new instance of class and assign values of each field from source object. This can be applied by “MemberwiseClone” method of object class.
For reference type fields, this operation causes “copying reference pointer” of field in source object. After copying, source field and destination field will be pointing to same referenced object in memory.
Code:
 class TestData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        List<int> iList;

        public TestData Clone()
        {
            TestData res = (TestData)this.MemberwiseClone();
            return res;
        }
    }

Deep Copy:
Creates a new instance of object in a totally “memory separated” manner. This operation should create copy of reference types in a way that referenced instance creates a copy of itself. When the creation is complete, there must be no reference in common with source and destination object.

If all the fields of the class are value types or string type, shallow and deep copying will end up with the same result.

In .NET,  there is no direct framework help for deep copying. Deep copying is generally implemented by “Serialization-Deserialization” technique. This technique is quite subtle and easily implemented. To be honest, I was impressed when I saw it for the first time. However it has its own drawbacks, such as:

n  All the reference types that are part of copying must be marked as serializable.
n  Serialization and deserialization are relatively slow methods.

Here is the code for “Serialization-Deserialization” method.
C# Code:
 public static object DeepCopyWithSerialization(object source)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, source);
                ms.Position = 0;
                object res = formatter.Deserialize(ms);
                return res;
            }

        }

I want to suggest another method which is implemented by using System.Reflection library. It is quite faster than serialization-deserialization method.
Main idea of this method is recursively creating copy of reference types until value type or string type is encountered. Here we make an exception for string class because all the strings that have the same value point to same memory area in .NET.
For initial copy of object, we need to use “MemberwiseClone” method of object class. Unfortunately, this method is protected. So we have to invoke this method by reflection over NonPublic binding flag.

C# Code:
static class DeepCopyHelper
    {
        static MethodInfo miMemberwiseClone;
        static Type stringType;
        static DeepCopyHelper()
        {
            miMemberwiseClone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
            stringType = typeof(string);
        }


        public static object DeepCopyWithReflection(object objSource)
        {
            object objDest = miMemberwiseClone.Invoke(objSource, null);
            FieldInfo[] fiArr = GetFields(objSource);
            foreach (FieldInfo fi in fiArr)
            {
                object readValue = fi.GetValue(objSource);
                if (readValue != null)
                {
                    Type typeSource = readValue.GetType();
                    if (typeSource.IsClass && !typeSource.Equals(stringType))
                    {
                        readValue = DeepCopyWithReflection(readValue);
                    }
                }
                fi.SetValue(objDest, readValue);
            }
            return objDest;
        }

        static FieldInfo[] GetFields(object obj)
        {
            Type t = obj.GetType();
            FieldInfo[] fiArr = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            return fiArr;
        }

    }

Sunday, March 17, 2013

Printing "Hello World" Without Using Semicolon (;)


This is an old question which has been asked C beginners. Actually, C code for “printing Hello World without using semicolon” is substantially easier than C# code. Here it is:
C Code:
#include <stdio.h>

void main(void)
{
 if (printf("Hello World"))
 {
 }
}

The main advantage here is that printf function returns a value, it is not void. However, Console.WriteLine function of C#, which is equivalent to printf of C, does NOT return a value. It is void.
So the question becomes, “How can I invoke WriteLine method of Console class so that the invocation returns a value?”.

The answer is “reflection”.  .NET refleciton library is quite robust for handling runtime metadata retrieveing, dynamic method invocation. Here, we need to use “MethodInfo” class, which represents a funciton of a class. MethodInfo has an “Invoke” function, which returns object!

Here is the code:

C# Code:
namespace nameSpaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (
                    typeof(System.Console).
                    GetMethod(
                            "WriteLine", new SystemType[] { typeof(string) })
                    .Invoke(
                        null,
                        new string[] { "Hello World!" })
                     == null
                )
            {

            }
        }
    }
}

Sunday, March 10, 2013

Efficient Way of Determining Whether a Collection Contains Element / Is Non-Empty


Determining “whether a collection is non-empty” is considered as one of the most basic and simple algorithms and generally coded as:


return collection.TakeCount() > 0;

               
For collections that can grow dynamically i.e. List, Dictionary, etc. such a code can be very costly in some circumstances.

If you’re using property of ICollection class, there is no problem. You can safely continue use them for framework collection classes since it keeps the count pre-calculated.

If you are using function of IEnumarable interface,  take a little notice. Because implementation of function over the .NET Framework collection classes calculate the count by iterating through all elements in the collection.

For collections that contain thousands or millions of element, that cost is highly redundant for such a simple “Is Non-Empty?” operation.

The code below determines “if the collection is non-empty” without counting and very quickly:

C# Code:
        static bool ContainsElement(IEnumerable coll)
        {
            if (coll == null)
            {
                return false;
            }

            foreach (var item in coll)
            {
                return true;
            }
            return false;
        }

A shortcut for IEnumerable<T> classes can be:

C# Code:
       static bool ContainsElement<T>(IEnumerable<T> coll)
        {
            return coll != null && coll.Any();
        }

Saturday, March 9, 2013

.NET Dictionary with Class Types as Key Type


In .NET, Dictionary<Tkey, Tvalue> class provides a hashed collection which improves the performance of read operations.

In most cases, type of the key element is a primitive type like int, string, long, etc. However in some scenarios, type of the key element needs to be a custom class that we implement.

In such cases, the programmer is responsible for generating “smooth” hash code and compare equality. So here, do you think programmer needs to write a “hash code generator algorithm” and dwell upon minimizing collision of generated indices?


Here is a neat implementation:
In the class, we already know the members which provide equality and we also know that each of them has GetHashCode() method.  By invoking the GetHashCode() method on each of them and by joining them, we can solve the problem of generating hash code complexity.

The operation that I mentioned as “joining hash codes” is generally implemented as applying bitwise Exclusive OR (XOR) against hash codes because it provides even distribution of generated indices.


C# Code:
class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public override bool Equals(object obj)
        {
            Item other = (Item)obj;
            return this.Id == other.Id &&
                   this.Name == other.Name;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode() ^ Name.GetHashCode();
        }
    }

For all the instances of Item class who has equal values for both Id and Name properties, the equal hash codes will be generated and they will be treated as same "key" by .NET dictionary.