.NET ez 2011-11-30
當多個執行緒共用變數使用Lock及Monitor,可以達到鎖定的效果!
但如果此時有執行緒需要讀取變數,就需要等待Lock結束後才能進行讀取,造成單一時間只能有一個執行緒動作,系統自然會降低效能,此時就能採用ReaderWriterLock ,即可解決問題。
ReaderWriterLock 允許同時間讓執行緒進行鎖定及讀取動作,如果執行緒不常寫入,大部份的時間都在讀取,那效能會優於Lock及Monitor!
using System; using System.Collections.Generic; using System.Threading; namespace Test { class Program { static void Main(string[] args) { ReaderWriterLock rwLock = new ReaderWriterLock(); int count = 0; List<Thread> List_Thread = new List<Thread>(); for (int i = 0; i < 10; i++) { //建立執行緒 List_Thread.Add(new Thread(() => { int temp = 10000; while (temp-- > 0) { rwLock.AcquireWriterLock(Timeout.Infinite); //開始鎖定 count++; rwLock.ReleaseWriterLock(); //結束鎖定 } })); List_Thread[i].Start(); } //等待所有執行緒完成 foreach (Thread t in List_Thread) t.Join(); Console.WriteLine(count.ToString()); Console.ReadLine(); } } }
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Mulit-Thread-ReaderWriterLock-Variable
https://www.ez2o.com/Blog/Post/52
https://www.ez2o.com/Blog/Post/csharp-Mulit-Thread-ReaderWriterLock-Variable
https://www.ez2o.com/Blog/Post/52