Windows Phone Developers

Thursday, September 22, 2011

Threading in .NET/C# - How to get Thread Details

How to Execute a process in separate thread in VB.NET/C#

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 Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

1 comment:

  1. Great article, its very useful.

    We can submit our .net related article links on http://www.dotnettechy.com to get more traffics.

    ReplyDelete