This was one of my favorites - Threading; but somehow I ignored for long. Now let us delve into it
Let us execute some small piece of code (a definite loop) through normal method and with the help of threading. Normal methid
private void ThreadExampleSync() { for (int iCnt = 0; iCnt < 3; iCnt++) { for (int j = 0; j < 100; j++) { for (int j1 = 0; j1 < 9000000; j1++) { } } Console.WriteLine("Iteration {0} is executed by {1} at {2}", iCnt.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString()); } }When we move to threading let us take the looping part into a separate method and call the method using different Threads
private void ThreadExampleAsync() { for (int iCnt = 0; iCnt < 3; iCnt++) { var t1 = new Thread(ExecuteTasks); t1.Start(iCnt); } } private static void ExecuteTasks(object iInput) { for (int j = 0; j < 100; j++) { for (int j1 = 0; j1 < 9000000; j1++) { //nothing } } Console.WriteLine("Iteration {0} is executed by {1} at {2}", iInput.ToString(), Thread.CurrentThread.ManagedThreadId.ToString(), DateTime.Now.ToString()); }
Since we are calling new thread for each iteration - ExecuteTasks gets executed by different threads as shown below
The time taken when we use different threads is faster than the synchronous way. However, care must be taken in Threading to avoid excess memory usage/leakages