C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In C#, the System.Threading
namespace provides the Thread
class and other thread-related classes for creating, managing, and synchronizing multiple threads. Multithreading enables your program to perform tasks concurrently, which can improve performance and responsiveness. In this tutorial, we'll cover the basics of working with threads in C#.
To create a new thread, you need to instantiate the Thread
class and provide a ThreadStart
or ParameterizedThreadStart
delegate, which represents the method that the thread will execute.
using System; using System.Threading; class Program { static void Main() { Thread thread = new Thread(new ThreadStart(DoWork)); thread.Start(); } static void DoWork() { Console.WriteLine("Thread started."); } }
To pass parameters to a thread, use the ParameterizedThreadStart
delegate and the Start
method.
using System; using System.Threading; class Program { static void Main() { Thread thread = new Thread(new ParameterizedThreadStart(DoWork)); thread.Start("Hello, World!"); } static void DoWork(object message) { Console.WriteLine($"Thread received: {message}"); } }
Thread synchronization is important to ensure that multiple threads do not interfere with each other when accessing shared resources. One common synchronization technique is to use the lock
statement, which ensures that only one thread can access the protected code block at a time.
using System; using System.Threading; class Program { private static readonly object _lock = new object(); private static int _counter = 0; static void Main() { Thread thread1 = new Thread(new ThreadStart(IncrementCounter)); Thread thread2 = new Thread(new ThreadStart(IncrementCounter)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); Console.WriteLine($"Counter: {_counter}"); } static void IncrementCounter() { for (int i = 0; i < 1000; i++) { lock (_lock) { _counter++; } } } }
The Thread.Sleep
method is used to pause the current thread for a specified amount of time. This can be useful for simulating work, waiting for a resource to become available, or implementing a delay.
using System; using System.Threading; class Program { static void Main() { Console.WriteLine("Starting work..."); Thread.Sleep(2000); // Sleep for 2 seconds Console.WriteLine("Work completed."); } }
The ThreadPool
class provides a pool of worker threads that can be used to execute tasks in parallel. This can help improve performance by reducing the overhead of creating and destroying threads.
using System; using System.Threading; class Program { static void Main() { ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), "Task 1"); ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), "Task 2"); Thread.Sleep(3000); // Give the tasks time to complete } static void DoWork(object state) { Console.WriteLine($"Thread received: {state}"); } }
How to create a thread with ThreadStart in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = new ThreadStart(MyThreadFunction); Thread myThread = new Thread(threadStart); myThread.Start(); } static void MyThreadFunction() { Console.WriteLine("Thread is running!"); } }
Using ThreadStart delegate in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = new ThreadStart(MyThreadFunction); Thread myThread = new Thread(threadStart); myThread.Start(); } static void MyThreadFunction() { Console.WriteLine("Thread is running!"); } }
ThreadStart vs. lambda expressions in C#
using System; using System.Threading; class Program { static void Main() { Thread myThread = new Thread(() => Console.WriteLine("Thread with lambda is running!")); myThread.Start(); } }
Creating parameterized threads with ThreadStart in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = new ThreadStart(() => MyThreadFunction("Hello from thread!")); Thread myThread = new Thread(threadStart); myThread.Start(); } static void MyThreadFunction(object parameter) { Console.WriteLine(parameter); } }
Passing parameters to ThreadStart in C#
using System; using System.Threading; class Program { static void Main() { Thread myThread = new Thread(MyThreadFunctionWithParameter); myThread.Start("Hello from thread!"); } static void MyThreadFunctionWithParameter(object parameter) { Console.WriteLine(parameter); } }
Starting and stopping threads with ThreadStart in C#
using System; using System.Threading; class Program { static void Main() { Thread myThread = new Thread(MyThreadFunction); myThread.Start(); Thread.Sleep(2000); // Allowing the thread to run for 2 seconds myThread.Abort(); // Stopping the thread } static void MyThreadFunction() { while (true) { Console.WriteLine("Thread is running!"); Thread.Sleep(500); } } }
ThreadStart and asynchronous operations in C#
using System; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main() { ThreadStart threadStart = new ThreadStart(() => MyThreadFunction().Wait()); Thread myThread = new Thread(threadStart); myThread.Start(); Console.WriteLine("Main thread is not blocked!"); Console.ReadLine(); } static async Task MyThreadFunction() { await Task.Delay(2000); Console.WriteLine("Thread is running asynchronously!"); } }
ThreadStart and anonymous methods in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = delegate { Console.WriteLine("Thread with anonymous method is running!"); }; Thread myThread = new Thread(threadStart); myThread.Start(); } }
ThreadStart and method references in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = MyThreadFunction; Thread myThread = new Thread(threadStart); myThread.Start(); } static void MyThreadFunction() { Console.WriteLine("Thread is running!"); } }
C# ThreadStart and thread safety
using System; using System.Threading; class Program { static int counter = 0; static object lockObject = new object(); static void Main() { ThreadStart threadStart = IncrementCounter; Thread thread1 = new Thread(threadStart); Thread thread2 = new Thread(threadStart); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); Console.WriteLine("Final Counter: " + counter); } static void IncrementCounter() { for (int i = 0; i < 100000; i++) { lock (lockObject) { counter++; } } } }
ThreadStart and exception handling in C#
using System; using System.Threading; class Program { static void Main() { ThreadStart threadStart = MyThreadFunction; Thread myThread = new Thread(threadStart); try { myThread.Start(); } catch (Exception ex) { Console.WriteLine("Exception caught: " + ex.Message); } } static void MyThreadFunction() { throw new Exception("Simulated exception in thread!"); } }
ThreadStart and background threads in C#
using System; using System.Threading; class Program { static void Main() { Thread myThread = new Thread(MyThreadFunction); myThread.IsBackground = true; // Set the thread as a background thread myThread.Start(); Console.WriteLine("Main thread is not blocked!"); Console.ReadLine(); } static void MyThreadFunction() { while (true) { Console.WriteLine("Thread is running!"); Thread.Sleep(500); } } }
ThreadStart and thread priority in C#
using System; using System.Threading; class Program { static void Main() { Thread myThread = new Thread(MyThreadFunction); myThread.Priority = ThreadPriority.AboveNormal; // Set thread priority myThread.Start(); } static void MyThreadFunction() { Console.WriteLine("Thread is running!"); } }