lock关键 (lock的本质就是Monitor,另外Monitor,Mutex也是排它锁,相比之下Mutex是夸进程的)
1 lock(this) 2 { 3 Callback(" A-" + count.ToString()); 4 }
ILspy下看到的
1 bool flag = false; 2 try 3 { 4 Monitor.Enter(this, ref flag); 5 this.Callback(" A-" + i.ToString()); 6 } 7 finally 8 { 9 if (flag) 10 { 11 Monitor.Exit(this); 12 } 13 }
Task取消
1 CancellationTokenSource tokenSource = new CancellationTokenSource(); 2 CancellationToken token = tokenSource.Token; 3 Task task = new Task(() => 4 { 5 try 6 { 7 for (int i = 0; i < int.MaxValue; i++) 8 { 9 if (token.IsCancellationRequested) 10 { 11 Console.WriteLine("task is cancel"); 12 token.ThrowIfCancellationRequested(); 13 } 14 else 15 { 16 Console.WriteLine("Int value {0}", i); 17 } 18 } 19 } 20 catch(OperationCanceledException) 21 { 22 Console.WriteLine("cancelling task callback"); 23 } 24 }, token); 25 26 Console.WriteLine("Press enter to start task"); 27 Console.WriteLine("Press enter again to cancel task"); 28 Console.ReadKey(); 29 task.Start(); 30 31 Console.ReadKey(); 32 tokenSource.Cancel();
For 线程取消
Task并行
1 static void DoAction(int i) 2 { 3 Thread.Sleep(300* i); 4 Console.WriteLine("msg:" + i.ToString()); 5 } 6 7 Parallel.For(0, 10, i => DoAction(i));
Task串行
1 static int Task1(object state) 2 { 3 int i = (int)state; 4 5 Thread.Sleep(100* (10-i)); 6 Console.WriteLine("task1:" + i.ToString()); 7 i += 1; 8 return i; 9 } 10 11 static int Task2(Task<int> t) 12 { 13 var i = t.Result; 14 Console.WriteLine("task2:" + i.ToString()); 15 Thread.Sleep(100*(11-i)); 16 i *= 10; 17 return i; 18 } 19 20 static Task<int> MergerTask(object input) 21 { 22 Task<int> t = new Task<int>(Task1, input); 23 var t2 = t.ContinueWith<int>(Task2); 24 t.Start(); 25 return t2; 26 } 27 28 static async void DoTask(int input) 29 { 30 var result= await MergerTask(input); 31 Console.WriteLine("merger-task:"+ input +" result: "+ result); 32 }
调用
1 for (int i = 1; i < 10; i++) 2 { 3 DoTask(i); 4 }
线程量行--Semaphore 限制同一时间内只能跑几个线程,用于排队类型
1 static Semaphore _sem = new Semaphore(3, 3); 2 static void Enter(object id) 3 { 4 Console.WriteLine(id + " waitting..."); 5 _sem.WaitOne(); 6 Console.WriteLine(id + " is in!"); 7 Thread.Sleep(1000 * (int)id); 8 Console.WriteLine(id + " is leaving"); 9 _sem.Release(); 10 }
调用
1 for (int i = 1; i <= 10; i++) 2 { 3 new Thread(Enter).Start(i); 4 }
时间: 2024-10-08 04:24:16