在讲CancellationTokenSource之前我决定先讲一下lock和Interlocked,如果能很好的理解这两个,再去理解CancellationTokenSource就会方便很多,由于我也是后起使用多线程,使用的时候就是直接运用FramWork4的东西,这样导致了很多东西学起来很吃力,当回顾了以前的知识点后,发现新出的东西如此好理解。
先看一下Lock的使用,下面是一个例子。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LockConsole { class Program { static object lockint = 0; static void Main() { Task[] tlist=new Task[10]; Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { var action = new Action<object>(Withdraw); Task t = new Task(action, i); tlist[i] = t; //Thread t = new Thread(new ThreadStart(acc.DoTransactions)); //threads[i] = t; } for (int i = 0; i < 10; i++) { tlist[i].Start(); //threads[i].Start(); } Console.Read(); } static void Withdraw(object i) { int amount = int.Parse(i.ToString()); int balance = 1000; lock (lockint)//删除lock就会造成 线程混乱 { if (balance >= amount) { Console.WriteLine("当前线程{0},当前状态{1}", Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.ThreadState + "Balance before Withdrawal : " + balance); Console.WriteLine("当前线程{0},当前状态{1}", Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.ThreadState + "Amount to Withdraw : -" + amount); balance = balance - amount; Console.WriteLine("当前线程{0},当前状态{1}", Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.ThreadState + "Balance after Withdrawal : " + balance); } } } } }