Home / C Sharp / Archive by category 'C# Threading'

C# Threading

Creating multiple threads in C#

The following is an example on how multiple threads can be created in csharp within a for loop. This demonstrates how a single function is invoked by multiple threads.

static void doWork()
{
    Console.WriteLine("Thread id of current thread is {0}", Thread.CurrentThread.ManagedThreadId);
}
 ThreadStart Op = new ThreadStart(doWork);
 
for(int i = 0; i < 5; i++)
{
    Thread myThread = new Thread(Op);
    myThread.Start();
}

Output:

Thread id of current thread is 2
Thread id of current thread is 3
Thread id of current thread is 4
Thread id of current thread is 5
Thread id of current thread is 6

The output thread ids are consecutive because the function invoked is very small and completed quickly.


Creating a simple thread in C#

The System.Threading class contains all the necessary methods and properties needed to create and manage threads in csharp. The general method of creating a thread is as follows:

1. Create a static method with a void return type that can be used to perform all the work needed to be performed by the thread.
2. Create a ThreadStart delegate that can use the above method.
3. Create a Thread Object by specifying the ThreadStart object.
4. Invoke the Thread.Start to begin execution of the created thread.

static void doWork()
{
    Console.WriteLine("Thread id of current thread is {0}", Thread.CurrentThread.ManagedThreadId);
}
ThreadStart Op = new ThreadStart(doWork);
Thread myThread = new Thread(Op);
myThread.Start();

The ManagedThreadId is a number assigned to every thread that is created.