• 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();
            }
        }
     
  • 相关阅读:
    服务器建设问题
    JDBC --反射(二)
    Cookies
    http和https区别
    springboot常用注解
    线程池
    悲观锁和乐观锁
    java高并发下的数据安全
    idea解决mybatis逆向工程
    spring Cloud
  • 原文地址:https://www.cnblogs.com/dangnianxiaoqingxin/p/12588766.html
Copyright © 2020-2023  润新知