1
我打電話給我的後臺工作由下面的代碼:串口工作線程凍結隨機
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 { }
}
沒有任何情況反覆添加DataReceived事件處理程序將會很好地結束。 –
'connection.DataReceived + = new SerialDataReceivedEventHandler(DataReceivedEvent);'關注我。你有沒有刪除這些處理程序? – aquinas
也許這並不重要,但對於DoWork()的每次調用,您都會向connection.DataReceived添加一個事件處理程序,但不會將其移除。你可以發佈DataReceivedEvent()的代碼嗎? –