2012-09-30 58 views
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 { } 
} 
+2

沒有任何情況反覆添加DataReceived事件處理程序將會很好地結束。 –

+0

'connection.DataReceived + = new SerialDataReceivedEventHandler(DataReceivedEvent);'關注我。你有沒有刪除這些處理程序? – aquinas

+0

也許這並不重要,但對於DoWork()的每次調用,您都會向connection.DataReceived添加一個事件處理程序,但不會將其移除。你可以發佈DataReceivedEvent()的代碼嗎? –

回答

0

好了,因爲沒有人留下了一個答案,我會的。問題是行

connection.DataReceived += new SerialDataReceivedEventHandler(DataReceivedEvent); 

在後臺工作者的計時器的每個滴答中被調用。這將導致事件處理程序的大量實例,這最終會導致後臺工作人員始終鎖定並報告忙碌事件。爲了糾正這個問題,我需要輸入

connection.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedEvent); 

爲了避免有大量事件處理程序處理數據接收事件。這已經解決了我的問題。