C# task多线程创建,暂停,继续,结束使用

1、多线程任务创建

 private void button1_Click(object sender, EventArgs e) //创建线程
        {

            CancellationToken cancellationToken = tokensource.Token;
            Task.Run(() =>  //模拟耗时任务
            {
                for (int i = 0; i < 100; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    m.WaitOne(); //当m等于true,才会往下执行,否则一直在此等待
                    textBox1.Text = i.ToString();
                    Thread.Sleep(1000);
                }
            }, cancellationToken);//绑定令牌到多线程
        }

2、线程暂停

 private void button2_Click(object sender, EventArgs e) //暂停线程
        {
            m.Reset();  //阻塞线程
        }

3、线程继续

   private void button3_Click(object sender, EventArgs e) //继续线程
        {
            m.Set();
        }

4、取消线程

   private void button4_Click(object sender, EventArgs e) //取消线程
        {
            tokensource.Cancel();
        }

完整版代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        ManualResetEvent m = new ManualResetEvent(true); //实例化阻塞事件
        CancellationTokenSource tokensource=new CancellationTokenSource(); //声明令牌
      
        private void button1_Click(object sender, EventArgs e) //创建线程
        {

            CancellationToken cancellationToken = tokensource.Token;
            Task.Run(() =>  //模拟耗时任务
            {
                for (int i = 0; i < 100; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    m.WaitOne(); //当m等于true,才会往下执行,否则一直在此等待
                    textBox1.Text = i.ToString();
                    Thread.Sleep(1000);
                }
            }, cancellationToken);//绑定令牌到多线程
        }

        private void button2_Click(object sender, EventArgs e) //暂停线程
        {
            m.Reset();  //阻塞线程
        }

        private void button3_Click(object sender, EventArgs e) //继续线程
        {
            m.Set();
        }

        private void button4_Click(object sender, EventArgs e) //取消线程
        {
            tokensource.Cancel();
        }
    }
}

软件界面如下

C# task多线程创建,暂停,继续,结束使用_第1张图片

你可能感兴趣的:(多线程的应用,c#,开发语言)