c#跨线程访问控件,为什么Thread对象不能写在方法里面

代码如下.(若将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);
}

}

}
}

线程如果是个死循环 你想想程序会不会一直卡在某个语句不动了呢 线程虽然独立于主UI线程 但是你启动线程的语句在程序执行的过程中是要跳出的 否则会卡在t1.start();这一行 那样你如何修改btn的caption追问

为什么说当线程是个死循环的时候,程序会一直卡在某个语句不动了?为什么会不动了呢?CPU不是会强制切换线程的吗.
还有,我还是不明白,当Thread t1 = null;写在button1_click()方法里面 当第二次单击(即我想暂停线程),但此时若没有写t1=null判断时,button1_click()方法会有“System.NullReferenceException”异常.

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答