【发布时间】:2015-02-09 14:26:06
【问题描述】:
我正在用 C# 构建一个使用 Excel 运行的应用程序,最终游戏是允许用户单击 Excel 工作表上的按钮,然后通过串行端口发送一些命令,然后读回数据。
这已经完成并且工作正常。
我的问题是,我如何检查以确保在应用程序关闭之前没有在 serialport_DataReceived; 事件上运行任何事件/函数,就好像它们那样我会遇到异常崩溃 -
The I/O operation has been aborted because of either a thread exit or an application request.
所以,在某种程度上,我需要进行某种清理,说明串行端口仍在收集数据,等到完成后再关闭。
这是我目前的代码;
while (!dataCollected)
{
if (data.Contains(carrier)) // If the read data doesn't contain end carriage return, then retry until it does
{
if (data.Contains(resultMessage)) // Check to make sure it has the result message - this guarantees a fully built read data with no missing bytes
{
ParseIncomingDataToExcel(data); // put the string into a specfic excel row
dataCollected = true; // exits out of the while loop
}
}
else // Carriage not found, data loss - try again
{
data = wrench.ReadLine();
}
}
if (dataCollected)
SetControlPropertyValue(button, "Enabled", true); // Invoke to turn the button enabled to true
所以基本上,你通过串口发送一个命令,然后得到一个输出。如果你在这个过程中尝试退出,那么它会给出一个异常(我知道这会发生,我宁愿把代码放进去阻止它发生,而不是把它放在一个 try 块中
private void Sheet1_Shutdown(object sender, System.EventArgs e)
{
dataCollected = true;
wrench.Close();
}
这会使程序在尝试关闭串行端口上的连接时挂起...如果我删除 wrench.close - 则显示上述异常(如我所料)。
--编辑--
我尝试在我的 while 循环中将我的布尔值声明为全局 volatile 类型,但我对使用这样的东西有一种不好的感觉,似乎是一种 hack(并且仍然不起作用,只是挂起.. .)
【问题讨论】:
标签: c# serial-port