线程启动停止暂停

private CancellationTokenSource cts;
private ManualResetEvent mr = new ManualResetEvent(true);

private int current;
public int Current
{
  get {
        return current;
       }
    set 
    {

        current = value;
        this.Invoke(new Action(() =>
        {
            this.progressBar1.Value = Current;

            this.label2.Text = Current.ToString();

        }));

    }

}
      
//启动
private void button1_Click(object sender, EventArgs e)
{

    cts = new CancellationTokenSource();
    Task t1 = Task.Run(()=> 
    {

        ThMethod();
    
    },cts.Token);
}

private void ThMethod()
{
   while(!cts.IsCancellationRequested)
    {
        mr.WaitOne();
        Current++;
        if(Current>=200)
        {
            Current = 0;
        }
        Thread.Sleep(100);
    }


}

//停止
private void button2_Click(object sender, EventArgs e)
{
    cts.Cancel();
    Current = 0;
      
}

//暂停
private void button3_Click(object sender, EventArgs e)
{
    mr.Reset();
}

//继续
private void button4_Click(object sender, EventArgs e)
{
    mr.Set();
}

你可能感兴趣的:(C#,Winform,c#,数据库,开发语言)