Last active
August 14, 2018 03:28
-
-
Save poychang/806c9e688755e93138a9af5c56dec6b7 to your computer and use it in GitHub Desktop.
[執行緒同步資源鎖定 lock / SyncLock 範例] #dotnet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// REF: [C#.NET][Thread] 執行緒同步資源鎖定 lock / SyncLock | |
// https://dotblogs.com.tw/yc421206/2011/01/07/20624 | |
private static List<Thread> _threads = new List<Thread>(); | |
private static object _thisLock = new object(); | |
static void Main() | |
{ | |
for (int i = 0; i < 5; i++) | |
{ | |
var t = new Thread(new ParameterizedThreadStart(DoWorker)); | |
t.Name = i.ToString(); | |
t.Start(i); | |
_threads.Add(t); | |
} | |
// foreach (var item in _threads) | |
// { | |
// Console.WriteLine($"Thread[{item.ManagedThreadId}]: {item.ThreadState}"); | |
// Thread.Sleep(200); | |
// } | |
Console.WriteLine("Main thread exits.\n"); | |
Console.Read(); | |
} | |
private static void DoWorker(object num) | |
{ | |
lock (_thisLock) { | |
var thread = Thread.CurrentThread; | |
Console.WriteLine($"No.{num}-Thread[{thread.ManagedThreadId}]: Enter DoWorker method, State:{thread.ThreadState}"); | |
Thread.Sleep(1000); // 模擬執行緒在這一個方法占用了很多時間 | |
// 不斷地觀察執行緒的生命週期 | |
foreach (var item in _threads) | |
{ | |
Console.WriteLine($"Thread[{item.ManagedThreadId}]: {item.ThreadState}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment