Esempio n. 1
0
        private void btnAbortableThreadPool_Click(object sender, EventArgs e)
        {
            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));

            WorkItem workItem1 = AbortableThreadPool.QueueUserWorkItem(new WaitCallback(Test));

            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));

            WorkItem workItem2 = AbortableThreadPool.QueueUserWorkItem(new WaitCallback(Test));
            WorkItem workItem3 = AbortableThreadPool.QueueUserWorkItem(new WaitCallback(Test));
            WorkItem workItem4 = AbortableThreadPool.QueueUserWorkItem(new WaitCallback(Test));
            WorkItem workItem5 = AbortableThreadPool.QueueUserWorkItem(new WaitCallback(Test));

            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));
            Thread.Sleep(1000);

            Console.WriteLine(AbortableThreadPool.Cancel(workItem1, false));
            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));
            Thread.Sleep(1000);

            Console.WriteLine(AbortableThreadPool.Cancel(workItem1, true));
            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));
            Thread.Sleep(1000);

            //AbortableThreadPool.CancelAll(true);//可取消所有任务
            AbortableThreadPool.Join(); //等待所有任务退出
            Console.WriteLine(string.Format("QueueCount:{0},WorkingCount:{1}", AbortableThreadPool.QueueCount, AbortableThreadPool.WorkingCount));
        }