程序员的知识教程库

网站首页 > 教程分享 正文

C#窗体多线程启动,暂停,继续,取消

henian88 2025-05-14 13:40:21 教程分享 4 ℃ 0 评论

新建一个工程

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 WindowsFormsApp2

{

public partial class Form1 : Form

{

//异步任务发送取消信号,从而安全地终止任务的执行

private CancellationTokenSource cts = new CancellationTokenSource();

//手动停止事件对象

private ManualResetEvent mResetEvent = new ManualResetEvent(true);

public Form1()

{

InitializeComponent();

CheckForIllegalCrossThreadCalls=false;

}

private void button1_Click(object sender, EventArgs e)

{

//启动

//暂停之后需要再次启动执行

if (cts.IsCancellationRequested)

{

cts = new CancellationTokenSource();

}

Task task = new Task(() => {

int count = 0;

while (!cts.IsCancellationRequested)

{

//用来控制是否需要继续和暂停

mResetEvent.WaitOne();

count++;

listBox1.Items.Add(count.ToString());

Thread.Sleep(1000);

}

}, cts.Token);

task.Start();

}

private void button2_Click(object sender, EventArgs e)

{

// 暂停

mResetEvent.Reset();

}

private void button3_Click(object sender, EventArgs e)

{

//继续

mResetEvent.Set();

}

private void button4_Click(object sender, EventArgs e)

{

//取消

cts.Cancel();

}

}

}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表