Today we will introduce two types of locks in C #: lock and ReadWriteLock)
Lock)
The lock keyword marks the statement block as a critical section to obtain the mutex lock of a given object, execute the statement, and then release the lock. When any thread obtains the lock, if other threads need to use the code in this critical section, they must wait for the previous thread to release the lock after use.
Sample Code:
Object thisLock = new Object (); lock (thisLock) {// code block in the critical section}
Read/write lock (ReadWriteLock)
ReadWriteLock defines the locks that support a single write thread and multiple read threads. This lock is mainly used to solve the performance problem of concurrent reads. Using this lock can greatly improve the performance of Concurrent Data access. It can only block all read locks when writing.
Sample Code:
Using System. Collections. Generic; using System. Windows; using System. Threading; namespace FYSTest {public partial class MainWindow: Window {List
List = new List
(); Private ReaderWriterLock _ rwlock = new ReaderWriterLock (); public MainWindow () {InitializeComponent (); Thread ThRead Thread = new ThRead (new ThreadStart (Read); Thread. isBackground = true; Thread ThRead2 = new Thread (new ThreadStart (Read); ThRead2.IsBackground = true; Thread ThWrite = new Thread (new ThreadStart (Write); ThWrite. isBackground = true; ThRead. start (); ThRead2.Start (); ThWrite. start ();} Private void Read () {while (true) {// use a System. Int32 timeout value to obtain the Read thread lock. _ Rwlock. acquirereaderlocks (100); try {if (list. count> 0) {int result = list [list. count-1] ;}} finally {// reduce lock Count and release lock _ rwlock. releaseReaderLock () ;}} int WriteCount = 0; // Number of writes private void Write () {while (true) {// use a System. get the write thread lock with the Int32 timeout value. _ Rwlock. acquireWriterLock (100); try {list. add (WriteCount ++);} finally {// reduce the lock count of the write thread lock and release the write lock _ rwlock. releaseWriterLock ();}}}}}