挂起/恢复线程的问题,关于ThreadState的状态,求指教!
using System;using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
//在单步调试过程中,实际上单击挂起线程按钮时,还未执行函数内的语句,t.ThreadState的值已经变成Stopped。为什么呢?
namespace thread_state
{
public partial class Form1 : Form
{
private Thread t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Sample st = new Sample(listBox1); //实例化Sample类
t = new Thread(new ThreadStart(st.work)); //创建Thread对象
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; //注销此语句会出现错误,不知道为啥
}
private void button1_Click_1(object sender, EventArgs e)
{
t.Start();
button1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
if (t.ThreadState == ThreadState.Running) //线程已启动,它未被阻塞,并且没有挂起的 ThreadAbortException。
{
t.Suspend(); //挂起线程
// listBox1.Items.Add("线程已挂起");
button2.Enabled = false;
button3.Enabled = true;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (t.ThreadState == ThreadState.Suspended) //如果线程已挂起
{
t.Resume(); //继续已挂起的线程
button2.Enabled = true;
button3.Enabled = false;
//listBox1.Items.Add("线程已恢复");
}
}
private void button4_Click(object sender, EventArgs e)
{
if (t.IsAlive & t.ThreadState == ThreadState.Running) //IsAlive :如果此线程已启动并且尚未正常终止或中止,则为 true;否则为 false。
{
t.Abort();
listBox1.Items.Add("线程已停止");
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
}
}
}
public class Sample
{
private System.Windows.Forms.ListBox listBox1;
public Sample(System.Windows.Forms.ListBox a)
{
this.listBox1 = a;
}
public void work()
{
listBox1.Items.Add("Sample 的 work 线程正在运行");
}
}
}
// 在单步调试时,发现:单击按钮事件的if条件{ 。。。}括号的语句未被 执行,就是单击按钮时,线程的状态t.Thread直接就变成Stopped了,不知道为什么???