串口工作线程随机冻结

时间:2012-09-30 20:52:27

标签: c# multithreading serial-port backgroundworker

我通过以下代码调用我的后台工作人员:

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 { }
}

1 个答案:

答案 0 :(得分:0)

好的,既然没人留下答案,我会的。问题是这一行

connection.DataReceived += new SerialDataReceivedEventHandler(DataReceivedEvent);

在后台工作者的计时器的每个滴答声中被调用。这将导致事件处理程序的大量实例,这最终会导致后台工作程序锁定并始终报告忙。要解决这个问题,我需要输入

connection.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedEvent);

为了避免有许多事件处理程序处理数据接收事件。这解决了我的问题。