代码如下.(若将Thread t1 = null;写在button1_click()方法里面,,当第二次单击(即暂停线程),t1则为null.
namespace 窗体应用程序
{
delegate void DGSetLabel(string str);
public partial class Form1 : Form
{
DGSetLabel dgSetLabel = null;
public Form1()
{
InitializeComponent();
dgSetLabel = new DGSetLabel(Setlabel);
}
Thread t1 = null;
private void button1_Click(object sender, EventArgs e)
{
t1.IsBackground = true;
if (btnStart.Text == "开始")
{
t1 = new Thread(SetlabelSafety);
btnStart.Text = "停止";
t1.Name = "t1";
if (t1 != null)
{
t1.Start();
}
}
else if (btnStart.Text == "停止")
{
if (t1 != null)
{
btnStart.Text = "开始";
t1.Abort();
}
else
{
MessageBox.Show("t1==null");
}
}
}
private void Setlabel(string msg)
{
lblNum.Text = msg;
}
private void SetlabelSafety()
{
Random rnd = new Random();
while (true)
{
this.Invoke(dgSetLabel, rnd.Next(0, 10).ToString());
Thread.Sleep(100);
}
}
}
}
为什么说当线程是个死循环的时候,程序会一直卡在某个语句不动了?为什么会不动了呢?CPU不是会强制切换线程的吗.
还有,我还是不明白,当Thread t1 = null;写在button1_click()方法里面 当第二次单击(即我想暂停线程),但此时若没有写t1=null判断时,button1_click()方法会有“System.NullReferenceException”异常.