C# .NET Framework 3.5 下 Task 与 Semaphore 的简单例子
使用 Thread 的请参考另一个贴子:https://www.cnblogs.com/pencilstart/p/15865400.html
注意,由于 .NET 3.5下并没有官方实现的 Task 库,所以,是通过 VS 中 NuGet 取得的 非官方 实现的 Task 库,调用接口与官方.NET 4.0 后的应该是差不多的。
另外,Semaphore 的初始值为 1。
1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4 5 namespace testTask 6 { 7 class Program 8 { 9 Semaphore se = new Semaphore(1, 1); 10 11 void test() 12 { 13 object param1 = new object[] { "Thread A", 1000 }; 14 object param2 = new object[] { "Thread B", 20 }; 15 16 Action<object> a1 = (x) => TaskProc(x); 17 18 Task task1 = new TaskFactory().StartNew(a1, param1); 19 Task task2 = new TaskFactory().StartNew(a1, param2); 20 21 Task.WaitAll(task1, task2); 22 } 23 24 static void Main(string[] args) 25 { 26 Program p = new Program(); 27 28 p.test(); 29 30 Console.WriteLine("main end, mainthreadid = {0}", System.Threading.Thread.CurrentThread.ManagedThreadId); 31 } 32 33 void TaskProc(object args) 34 { 35 string name = (string)((object[])args)[0]; 36 int startdelay = (int)((object[])args)[1]; 37 38 Console.WriteLine("{0}: COME IN, threadid = {1}", name, System.Threading.Thread.CurrentThread.ManagedThreadId); 39 40 System.Threading.Thread.Sleep(startdelay); 41 42 Console.WriteLine("{0}: START, threadid = {1}", name, System.Threading.Thread.CurrentThread.ManagedThreadId); 43 44 for (int i = 0; i < 10; ++i) 45 { 46 se.WaitOne(); 47 48 Random r = new Random(); 49 50 int s = r.Next(50, 1000); 51 52 Console.WriteLine("{0}: i = {1}, sleep({2}), threadid = {3}", name, i, s, System.Threading.Thread.CurrentThread.ManagedThreadId); 53 54 System.Threading.Thread.Sleep(s); 55 56 se.Release(); 57 } 58 59 Console.WriteLine("{0}: END, threadid = {1}", name, System.Threading.Thread.CurrentThread.ManagedThreadId); 60 } 61 } 62 } 63 64 //Thread A: COME IN, threadid = 3 65 //Thread B: COME IN, threadid = 4 66 //Thread B: START, threadid = 4 67 //Thread B: i = 0, sleep(795), threadid = 4 68 //Thread B: i = 1, sleep(200), threadid = 4 69 //Thread A: START, threadid = 3 70 //Thread A: i = 0, sleep(250), threadid = 3 71 //Thread B: i = 2, sleep(670), threadid = 4 72 //Thread A: i = 1, sleep(127), threadid = 3 73 //Thread B: i = 3, sleep(260), threadid = 4 74 //Thread A: i = 2, sleep(227), threadid = 3 75 //Thread B: i = 4, sleep(462), threadid = 4 76 //Thread A: i = 3, sleep(478), threadid = 3 77 //Thread B: i = 5, sleep(836), threadid = 4 78 //Thread A: i = 4, sleep(611), threadid = 3 79 //Thread B: i = 6, sleep(760), threadid = 4 80 //Thread A: i = 5, sleep(320), threadid = 3 81 //Thread B: i = 7, sleep(658), threadid = 4 82 //Thread A: i = 6, sleep(383), threadid = 3 83 //Thread B: i = 8, sleep(638), threadid = 4 84 //Thread A: i = 7, sleep(364), threadid = 3 85 //Thread B: i = 9, sleep(278), threadid = 4 86 //Thread B: END, threadid = 4 87 //Thread A: i = 8, sleep(89), threadid = 3 88 //Thread A: i = 9, sleep(192), threadid = 3 89 //Thread A: END, threadid = 3 90 //main end, mainthreadid = 1 91 //请按任意键继续. . .