问题描述
上位机程序:实现数控机床数据的实时采集。
需求:实时采集,这里采用周期性采集方案。本案例采用 Timer 类实现间隔调用采集方法。
相关部分的程序如下(按如下顺序执行):
//定义发送机床数据定时器
private System.Threading.Timer sendToMachineTimer;
private void Connect_Click(object sender, EventArgs e)
{
ConnectToMachine();
// 实例化定时器
sendToMachineTimer = new System.Threading.Timer(SendDataToMachine, null, -1, 500);
}
private void ConnectToMachine()
{
……
sendToMachineTimer.Change(0, 500);
……
}
当程序执行到:
sendToMachineTimer.Change(0, 500);
报错:
在这里插入代码片System.NullReferenceException:未将对象引用设置到对象的实例
sendToMachineTimer 为 null
原因
本案例中出现错误的原因是:对象在使用之前未进行初始化
分析:
在一开始,只是声明了一个 Timer 类的对象 sendToMachineTimer ,并未对其进行实例化。说白了,目前是“有名无分”。
随后 Connet_Click 事件中调用 ConnectToMachine() 方法,在该方法中,直接执行语句:
sendToMachineTimer.Change(0, 500);
问题来了,sendToMachineTimer 刚刚只是有了“名”而已,并没有“实权”,即没有进行实例化。自然的,此时sendToMachineTimer 是无法调用 Timer 中的方法的。因而,直接报错。
解决方法
很明显,先对 sendToMachineTimer 进行实例化,有了“实权”以后,再来调用 Timer 的方法。
程序修改如下:
//定义发送机床数据定时器
private System.Threading.Timer sendToMachineTimer;
private void Connect_Click(object sender, EventArgs e)
{
// 实例化定时器
sendToMachineTimer = new System.Threading.Timer(SendDataToMachine, null, -1, 500);
ConnectToMachine();
}
private void ConnectToMachine()
{
……
sendToMachineTimer.Change(0, 500);
……
}