我正在使用线程做一个练习 GUI Oven 程序,我不确定我是否应该这样做,因为我想在加热过程正在进行时与 GUI 交互。当我尝试通过单击 btnStop_Click 中止线程时,它会引发 NullReference 异常:
System.NullReferenceException:对象引用未设置为对象的实例。
请就如何优雅地停止线程提出建议。谢谢。
代码:
public partial class Form1 : Form
{
private Thread t;
public Form1()
{
InitializeComponent();
}
// button to begin heating
private void btnStart_Click(object sender, EventArgs e)
{
if ((txtMin.Text) == "" || (txtSec.Text) == "")
{
MessageBox.Show("Please enter duration of heating");
}
else
{
t = new Thread(heatIt);
btnHeat.Enabled = false;
t.Start();
}
}
//stop heating
private void btnStop_Click(object sender, EventArgs e)
{
Heating heat = new Heating();
Form1 l = new Form1();
l.Subscribe(heat);
heat.stopHeat();
btnHeat.Enabled = true;
}
private void heatIt()
{
// heat food Implementation that calls the 'Heating' class
}
public void Subscribe(Heating m)
{
m.heatComplete += SignalHeatCompleted;
m.heatStop += SignalStop;
}
private void SignalHeatCompleted(Heating m, EventArgs e)
{
MessageBox.Show( "Done, please enjoy your food");
return;
}
private void SignalStop(Heating m, EventArgs e)
{
t.Abort();
MessageBox.Show("Heating Terminated");
return;
}
public class Heating
{
public event HeatingCompleted heatComplete; // Heating Completed Event
public event HeatingStop heatStop; // Heating Stop Event
public EventArgs e = null;
public delegate void HeatingCompleted(Heating h, EventArgs e);
public delegate void HeatingStop(Heating s, EventArgs e);
public void startHeat(int temp, int min, int sec)
{
int totalSec;
totalSec = ((min*60) + sec) * 1000;
Thread.Sleep(totalSec);
if (heatComplete != null)
{
heatComplete(this, e);
}
else
{
//Use default signal if there's no subscription to this event
MessageBox.Show("*TING*");
}
return;
}
public void stopHeat()
{
if (heatStop != null)
{
heatStop(this, e);
}
}
}
}
最佳答案
您正在停止单击事件中创建 Form1 的新实例,因此您正在与与开始单击中的 t 完全不同的 t 交谈。
您可能还希望拥有一个在 heatIt 中分配的 Heat 实例,然后在停止单击中使用该引用。
对于后台处理,您可能还想查看 BackgroundWorker class为您完成繁重的工作。
关于C# - 线程中止和 System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075888/