码迷,mamicode.com
首页 > 其他好文 > 详细

Task的暂停,继续,取消

时间:2020-03-28 19:42:45      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:code   invoke   run   pre   return   thread   text   click   sync   

 

.

        
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();
        }
    }

 

 
技术图片

Task的暂停,继续,取消

标签:code   invoke   run   pre   return   thread   text   click   sync   

原文地址:https://www.cnblogs.com/dangnianxiaoqingxin/p/12588766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!