首先窗体界面如下:
怎么实现“start”启动线程、“pause”暂停线程、“resume”恢复线程,“stop”停止线程,
直观现象是,按start启动计数,在右边输出,点pause,会暂停输出,然后点resume能够继续输出,点stop则停止输出(这时候再点resume没反应,只能点start开始重新输出)
下图是暂停,但是本人没法儿恢复继续输出
在此,小弟先行谢过了!
30
namespace Test { public partial class Form4 : Form { public Form4() { InitializeComponent(); Label.CheckForIllegalCrossThreadCalls = false; } Thread thread; ManualResetEvent ma; bool on_off = false; bool stop = false; private void button1_Click(object sender, EventArgs e) { thread = new Thread(Runtime); thread.Start(); } void Runtime() { for (int i = 1; i <= 100; i++) { if (stop) return; if (on_off) { ma = new ManualResetEvent(false); ma.WaitOne(); } textBox1.AppendText("计时 :" + i + "\r\n"); Thread.Sleep(100); } } private void button2_Click(object sender, EventArgs e) { on_off = true; textBox1.AppendText("暂停中 :\r\n"); } private void button3_Click(object sender, EventArgs e) { on_off = false; ma.Set(); textBox1.AppendText("继续计时 :\r\n"); } private void button4_Click(object sender, EventArgs e) { stop = true; textBox1.AppendText("停止计时 \r\n"); } } }
10
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace 线程挂起测试
{
public partial class Form1 : Form
{
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
多线程();
PT();
}
private void button2_Click(object sender, EventArgs e)
{
PD = false;
}
private void button3_Click(object sender, EventArgs e)
{
PD = true;
PT();
}
private void 多线程()//创建线程执行 计时
{
ThreadStart entry = new ThreadStart(计时);
Thread workThread = new Thread(entry);
workThread.IsBackground = true;
workThread.Start();
//a = workThread.GetHashCode();
}
private void 计时()
{
textBox1.Text = “逐个计数到100为止\r\n”;
for (int i = 0; i < 101; i++)
{
textBox1.Text += “逐秒计时” + i + “\r\n”;
Thread.Sleep(1000);
myResetEvent.WaitOne();
}
}
private bool PD = true; //false
private void 判断能否执行()
{
while (PD)
{
myResetEvent.Set();
}
}
private void PT()//创建后台线程执行 判断能否执行
{
ThreadStart entry = new ThreadStart(判断能否执行);
Thread workThread = new Thread(entry);
workThread.IsBackground = true;
workThread.Start();
}
}
}
退出线程没写 留给你本人写了 本人倒是想写直接退出程序