我通过以下代码调用我的后台工作人员:
private void UpdateDataTimer_Tick(object sender, EventArgs e)
{
if (!serialPortWorker.IsBusy)
{
serialPortWorker.RunWorkerAsync();
}
}
我的DoWork
活动如下:
private void serialPortWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Configures serial port
connection.BaudRate = 19200;
connection.DataReceived += new SerialDataReceivedEventHandler(DataReceivedEvent);
//Sends the commands for opening diagnostics
string[] init_commands = { "STRING", "STRING", "STRING", "STRING", "STRING" };
foreach (string command in init_commands)
{
connection.WriteLine(command + connection.NewLine);
Thread.Sleep(1000);
}
const string constant_message_section = "G03";
string[] command_list = { "62", "64", "5C" };
//Writes all commands to all radio addresses
foreach (int address in radioAddresses)
{
foreach (string command in command_list)
{
for (int i = 0; i < MAX_ATTEMPTS; i++)
{
connection.WriteLine(constant_message_section + address.ToString("X4") + command);
Thread.Sleep(500);
}
}
}
Thread.Sleep(1000); //Give a little time for all responses to come in
}
出于某种原因,在调用了几百UpdateDataTimer_Tick
次事件之后,它就不再运行了serialPortWorker
。我在 上放了一个调试器if (!serialPortWorker.IsBusy)
,它表明它serialPortWorker
仍然很忙。它一定是在DoWork
活动的某个地方挂了,对吧?任何想法为什么?
感兴趣的可以看下数据接收事件如下:
public void DataReceivedEvent(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string receive = sp.ReadLine();
try
{
Debug.Logger.WriteToDebug("Data Received Serial Port: " + receive);
}
catch { }
try
{
int unit_address = Int32.Parse(receive.Substring(1, 4), System.Globalization.NumberStyles.HexNumber);
if (radioAddresses.Contains(unit_address))
{
int radio_index = radioAddresses.IndexOf(unit_address) + 1;
int max_index = radio_index * 3;
integrityMonitor[radio_index] = DateTime.Now; //Last updated time
int message_data = 0;
if (receive.Contains("66"))
{
//Stuff
}
else if (receive.Contains("61"))
{
//Stuff
}
else if (receive.Contains("55"))
{
//Stuff
}
}
}
catch { }
}