CancelInvoke doesn't actually cancel anything
Hello, I have a function ReadDataFromBHI() that will initialize a serial port then open it, then uses InvokeRepeating to read the data at 3 sec intervals. It's working fine, the problem is it won't stop. I have a disconnect button that calls ClosePorts() when clicked. As you can see the ClosePorts() is supposed to cancelInvoke the ReadDataContinuously and has a Boolean flag that sets to false, this isn't working either. The ReadDataContinuously continues to read data and print to the console window. Any help getting this to stop?
Thanks
public class ReadPortData : MonoBehaviour // Comes here when 'connect' is clicked, to start reading serial port data { public TMP_Dropdown portName; public TMP_Dropdown baudRate; public TMP_Dropdown dataBits; public TMP_Dropdown stopBits; public TMP_Dropdown parity;
private string spName;
private int baud;
private int dB;
private int sB;
private string pRity;
private static bool connected;
public SerialPort sp = new SerialPort();
private void ReadDataFromBHI()
{
// First get the values that were selected on the pnlComms dropdowns
ClosePorts();
spName = portName.options[portName.value].text;
baud = int.Parse(baudRate.options[baudRate.value].text);
dB = int.Parse(dataBits.options[dataBits.value].text);
sB = int.Parse(stopBits.options[stopBits.value].text);
pRity = parity.options[parity.value].text;
sp.PortName = spName;
sp.BaudRate = baud;
sp.DataBits = dB;
sp.DtrEnable = true;
switch (sB)
{
case 0: sp.StopBits = StopBits.None; break;
case 1: sp.StopBits = StopBits.One; break;
case 2: sp.StopBits = StopBits.Two; break;
}
switch (pRity)
{
case "None": sp.Parity = Parity.None; break;
case "Odd": sp.Parity = Parity.Odd; break;
case "Even": sp.Parity = Parity.Even; break;
}
sp.Open();
Debug.Log(spName + sp.IsOpen);
connected = true;
InvokeRepeating("ReadDataContinuously", 3f, 3f);
}
public void ClosePorts() // Closes all the open ports
{
CancelInvoke("ReadDataContinuously");
connected = false;
string[] ports = SerialPort.GetPortNames();
foreach (string s in ports)
{
if (sp.IsOpen)
{
sp.Close();
Debug.Log(s + " is now closed");
}
else
{
Debug.Log(s + " is already closed");
}
}
}
public void ReadDataContinuously()
{
Debug.Log(connected);
if (connected)
{
string buf = "";
string s;
string witsItem;
string witsData;
buf += sp.ReadExisting();
Debug.Log(buf);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612213106im_/https://answers.unity.com/themes/thub/images/avi.jpg)