Multithreading - parallel execution of code, leveraging threads.
C# enables multithreading using following namespace:
1:
|
using System.Threading;
|
When multithreading might be useful?
When multithreading might be awkward?
Do not mix Threads and Processes
Thread - execution path within a process
Process - is an instance of a program
Threads are represented in C# by class Thread
1:
|
System.Threading.Thread
|
Run parameterless method in separate thread
1:
|
Thread(ThreadStart)
|
Run method with an object-type parameter in separate thread
1:
|
Thread(ParameterizedThreadStart)
|
Thread should be created with an entry point when new thread will start execution.
This entry point is outlined by following delegates:
1: 2: |
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(Object obj);
|
Once thread created it should be run for execution:
1: 2: |
var thread = new Thread(someEntryPoint);
thread.Start();
|
There are a number of ways to stop thread:
Creating thread consumes is an expensive operation. Thread pool cuts these overheads.
Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time