Task的暫停,繼續,取消


 

.

        
CancellationTokenSource tokenSource;
        CancellationToken token;
        ManualResetEvent resetEvent;
        public Form1()
        {
            InitializeComponent();
            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            resetEvent = new ManualResetEvent(true);
            button1.Text = "開始";
            button2.Text = "暫停";
            button3.Text = "繼續";
            button4.Text = "取消";
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            int i = 0;
            Task task = new Task(async () =>
            {
     
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    if (i == 100)
                    { 
                        return;
                    }
                    resetEvent.WaitOne();
                    await Task.Run(() => 
                    {
                        i += 1;
                        this.Invoke(new Action(()=> 
                            {
                                progressBar1.Value = i;
                            }));
                            Thread.Sleep(50);
                        
                    });
                   
                }
            }, token);
            task.Start();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            resetEvent.Reset();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            resetEvent.Set();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            tokenSource.Cancel();
        }
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM