Lecture Topics:
ThreadStart
, ParameterizedThreadStart
ThreadPool
lock
, Monitor
, and Interlocked
async
, await
Lab:
Threading enables concurrent execution of code, improving performance for CPU-intensive or I/O-bound operations.
ThreadStart:
A delegate used to start a thread with a method that takes no parameters.
Example:
using System.Threading;
void Work() => Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is working");
Thread thread = new Thread(new ThreadStart(Work));
thread.Start();
thread.Join(); // Wait for thread to complete
// Outputs: Thread X is working
ParameterizedThreadStart:
A delegate for methods accepting a single parameter.
Example:
void ProcessData(object data) => Console.WriteLine($"Processing {data} on thread {Thread.CurrentThread.ManagedThreadId}");
Thread thread = new Thread(new ParameterizedThreadStart(ProcessData));
thread.Start("Employee Data");
thread.Join();
// Outputs: Processing Employee Data on thread X
ThreadPool:
Manages a pool of reusable threads to reduce overhead.
Example:
ThreadPool.QueueUserWorkItem(state => Console.WriteLine($"ThreadPool thread {Thread.CurrentThread.ManagedThreadId}"));
Thread.Sleep(100); // Allow thread to run
// Outputs: ThreadPool thread X
Synchronizing Critical Data:
lock: Ensures only one thread accesses a critical section.
Example:
object syncLock = new object();
int counter = 0;
void Increment()
{
lock (syncLock)
{
counter++;
Console.WriteLine($"Counter: {counter}");
}
}
Thread t1 = new Thread(Increment);
Thread t2 = new Thread(Increment);
t1.Start(); t2.Start();
t1.Join(); t2.Join();
// Outputs: Counter: 1, Counter: 2 (order may vary)
Monitor: Provides finer control than lock
(equivalent to lock
internally).
Example:
Monitor.Enter(syncLock);
try
{
counter++;
Console.WriteLine($"Counter: {counter}");
}
finally
{
Monitor.Exit(syncLock);
}
Interlocked: Performs atomic operations (e.g., increment, decrement).
Example:
int counter = 0;
Interlocked.Increment(ref counter);
Console.WriteLine($"Counter: {counter}"); // Outputs: Counter: 1
Key Points:
Thread
offers low-level control but high overhead; ThreadPool
is preferred for short tasks.Thread.Sleep
or Join
for testing, not production.Why This Matters:
Task
and TPL are preferred in modern .NET.