C# 取消';我不会取消任何东西
我有一个函数C# 取消';我不会取消任何东西,c#,unity3d,C#,Unity3d,我有一个函数ReadDataFromBHI(),它将初始化一个串行端口,然后打开它,然后使用invokereepeating以3秒的间隔读取数据 它工作正常,问题是它不会停止 我有一个断开连接按钮,单击该按钮可调用closeport()。正如您所看到的,closeport()应该CancelInvoke读取数据连续并且有一个设置为false的布尔标志,这也不起作用。ReadDataContinuously继续读取数据并打印到控制台窗口 有人帮我阻止这一切吗? 谢谢 我尝试将布尔标志添加到Clos
ReadDataFromBHI()
,它将初始化一个串行端口,然后打开它,然后使用invokereepeating
以3秒的间隔读取数据
它工作正常,问题是它不会停止
我有一个断开连接按钮,单击该按钮可调用closeport()
。正如您所看到的,closeport()
应该CancelInvoke
读取数据连续
并且有一个设置为false的布尔标志,这也不起作用。ReadDataContinuously
继续读取数据并打印到控制台窗口
有人帮我阻止这一切吗?
谢谢
我尝试将布尔标志添加到ClosePorts()
方法并将其设置为false。这并不能阻止它
还尝试了CancelInvoke()
,但没有使用限定字符串
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);
}
}
}
我希望
CancelInvoke(“string”)
或布尔标志会阻止串行端口读取数据,两者都不起作用。只是一个一般提示:为了避免输入错误而不是文字字符串,请使用nameof(ReadDataContinuously)
。ReadDataFromBHI
在哪里/如何调用?derHugo,我不知道如何制作您建议的格式。我在这里只有几个帖子还在学习基础知识。ReadDataFromBHI()是从同一面板上另一个按钮(btnConnect)的单击事件调用的。我在面板上有两个按钮btnConnect和btnDisconnect。两者都附带了ReadPortData脚本。btnConnect OnClick指向ReadPortData.ReadDataFromBHI函数。btnDisconnect OnClick事件指向ReadPortData.ClosePorts函数。是否同时有多个ReadPortData
实例?我认为,invokereepeating
和CancelInvoke
是基于实例而不是基于静态的。我只有一个ReadPortData实例。当布尔标志设置为false Debug.Log(buf)时,它将正常工作,不再打印,但是Debug.Log(已连接)将继续每隔3秒打印一次,因此取消调用不起作用。