线程操作:开始;暂停;继续

笔记,别人的程序

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 TaskAdvanceDemo
{
    public partial class FrmTask : Form
    {

        private CancellationTokenSource tokenSource = new CancellationTokenSource();
        private ManualResetEvent resetEvent = new ManualResetEvent(true);

        public FrmTask()
        {
            InitializeComponent();
        }

        //启动线程
        private void btnStart_Click(object sender, EventArgs e)
        { 
            Task task = new Task(async () =>
            {
               while (true)
               {
                   if (!tokenSource.IsCancellationRequested)
                   {
                       resetEvent.WaitOne();

                       //在下面编写你要让线程完成的任务...
                       Console.WriteLine("任务执行中...");
                       await Task.Delay(1000);
                   }
               }
            }, tokenSource.Token);
            task.Start();

        }
        //暂停
        private void btnSuspend_Click(object sender, EventArgs e)
        {
            resetEvent.Reset();
            Console.WriteLine("--------------------------任务暂停----------------------------");
        }
        //继续
        private void btnContinue_Click(object sender, EventArgs e)
        {
            resetEvent.Set();
            Console.WriteLine("--------------------------继续执行----------------------------");
        }
        //结束线程
        private void btnCancel_Click(object sender, EventArgs e)
        {
            tokenSource.Cancel();

            Console.WriteLine("--------------------------线程结束----------------------------");
            this.btnStart.Enabled = false;
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值