1. 程式人生 > >Task 開始 停止

Task 開始 停止

button 停止 rem ger check true read tor call

註意點:需要將每個線程的 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(); }

Task 開始 停止