Understanding Threading in .NET Framework
Summary
Thread basics using followings:
- How to Create thread; use System.Thread() class and create an instance
- How to Join thread; use object.Join() to join threads.
- How to Suspend thread; use object.Sleep(<No of seconds>) to Suspend thread
- How to Kill thread; use object.Abort() to Suspend thread
- Using Interlocked class which uses Increment and decrement method to increment and decrement values.
Thread Synchronization using followings:
- Using Locks: allows to mark a lock on the critical section of the code(program), provides synchronization to an object and then to execute the lock is in effect.
- Using Monitor: allows to decide when to enter and exit the synchronization, and it lets us wait for another area of code to become free. Monitor acts as a smart lock on a resource. When the we need synchronization, we can call the enter() method of the monitor passing the object we want to monitor. We can explicitly choose to wait () method of the monitor to control thread ordering. In case of using wait () waiting threads will be allowed to notified of a chance to run again if the active thread calls Pulse (). This signals the CLR that there has been a chance in the state that might free a thread that is waiting. The CLR tracks of the fact that the earlier thread asked to wait, and the thread will be guaranteed access in the order in which the wait where requested. Exit () can be called once when the thread is finished with the monitor.