注意点:需要将每个线程的 MemoryCacheManager 保存,这里我保存在缓存中,需要取消时根据缓存key值取出 MemoryCacheManager
//开始Task1 private void button1_Click(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false;//winform运行跨线程 ICacheManager cacheManager = new MemoryCacheManager(); var cts1 = new CancellationTokenSource(); CancellationToken ct1 = cts1.Token; Task.Factory.StartNew(() => { while (true) { Thread.Sleep(500); listView1.Items.Add("AA当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ct1.IsCancellationRequested) { // another thread decided to cancel listView1.Items.Add("task1 canceled"); cacheManager.Remove("cts1"); break; } } }, ct1); if (!cacheManager.IsSet("cts1")) { cacheManager.Set("cts1", cts1, 20); } } //开始Task2 private void button2_Click(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false;//winform运行跨线程 ICacheManager cacheManager = new MemoryCacheManager(); var cts2 = new CancellationTokenSource(); CancellationToken ct2 = cts2.Token; Task.Factory.StartNew(() => { while (true) { Thread.Sleep(500); listView1.Items.Add("BB当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ct2.IsCancellationRequested) { // another thread decided to cancel listView1.Items.Add("task1 canceled"); cacheManager.Remove("cts2"); break; } } }, ct2); if (!cacheManager.IsSet("cts2")) { cacheManager.Set("cts2", cts2, 20); } } //停止Task1 private void button3_Click(object sender, EventArgs e) { ICacheManager cacheManager = new MemoryCacheManager(); var cts = cacheManager.Get<CancellationTokenSource>("cts1"); cts.Cancel(); } //停止Task2 private void button4_Click(object sender, EventArgs e) { ICacheManager cacheManager = new MemoryCacheManager(); var cts = cacheManager.Get<CancellationTokenSource>("cts2"); cts.Cancel(); }