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();
View Code For 线程取消

相关文章: