Friday, May 8, 2009

Creating Threads in C#

Creating Threads


Creating a thread in C# is close to trivial, but not quite. The only non-trivial thing about
creating a thread is dotNet delegate-classes. Let me explain in few words what is a
delegate class. The delegate is a wrapper around a code construct in the dotNet. The code
construct could be an object instance, an instance method or a static method. Delegates
are used when you want to pass one of the three code constructs as a parameter to
another method.
When creating a new thread you have to use the ThreadStart delegate class to wrap the
instance method that will be executed in the newly created thread. The instance method
must return void and must not have any parameters.


void ThreadStart()
To create a new thread, first create a new ThreadStart object, passing the instance method
of the thread procedure in the constructor. The new delegate object is then passed to the
constructor of the Thread.


Thread thread = new Thread(
new ThreadStart(obj.ThreadStart));


You’ve now created a new thread, but the thread is not yet started. To start the thread,
you call the Thread.Start instance method.
thread.Start();

 

using System;

using System.Threading;

namespace ConsoleApplication1

{

    class Class1

    {

        static void PrintHelloFromThreadName()

        {

            Console.WriteLine("Hello, from thread {0}",

            Thread.CurrentThread.Name); // {0}

        }

        public void ThreadStart()

        {

         PrintHelloFromThreadName();

        }

 

        static void Main(string[] args)

        {

            Thread.CurrentThread.Name = "Main thread";

            Class1 obj = new Class1();

            Thread thread = new Thread(

            new ThreadStart(obj.ThreadStart));

            thread.Name = "Forked thread";

            thread.Start();

            PrintHelloFromThreadName();

        }

     }

 }


A nice feature of dotNet threads, and for that matter any dotNet object, is the ability name
the object. If you name your threads, then the debugger will pick up those names and
you’ll have a much easier time debugging

 

 

 

No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code