How to use Threads in C# to perform multiple operations simultaneously
This example shows how to use threads in C#, to perform multiple operations simultaneously.
Code:
using System;
using System.Threading;
namespace ConsoleApplications
{
class ThreadDemo
{
static void Main(string[] args)
{
// Create a main thread
Thread mainThread = Thread.CurrentThread;
mainThread.Name = "Main thread";
// Create a second thread
ThreadStart workerStart1 = new ThreadStart(PrintDot);
Thread workerThread1 = new Thread(workerStart1);
workerThread1.Name = "Worker thread (DOT)";
workerThread1.Start();
// Create a third thread
ThreadStart workerStart2 = new ThreadStart(PrintLine);
Thread workerThread2 = new Thread(workerStart2);
workerThread2.Name = "Worker thread (LINE)";
workerThread2.Start();
PrintLetters();
Console.WriteLine("The main thread has finished executing");
}
/// <summary>
/// This method, print X 10000 times
/// </summary>
static void PrintLetters()
{
for (int n = 0; n < 10000; n++)
Console.Write(" X ");
}
/// <summary>
/// This method, print . 10000 times
/// </summary>
static void PrintDot()
{
for(int n=0; n<10000; n++)
Console.Write(" . ");
Console.WriteLine("The worker thread has finished executing");
}
/// <summary>
/// This method, print - 10000 times
/// </summary>
static void PrintLine()
{
for (int n = 0; n < 10000; n++)
Console.Write(" - ");
Console.WriteLine("The worker thread has finished executing");
}
}
}
Note: The three methods will be run "simultaneously" in separate threads. The time it takes for each Thread is variable.