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();
}
}
}
软件界面如下文章来源:https://www.toymoban.com/news/detail-679741.html
文章来源地址https://www.toymoban.com/news/detail-679741.html
到了这里,关于C# task多线程创建,暂停,继续,结束使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!