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

1 回答 1

0

好的,既然没有人留下答案,我会的。问题是线路

connection.DataReceived += new SerialDataReceivedEventHandler(DataReceivedEvent);

在后台工作人员的计时器的每个滴答声中被调用。这将导致事件处理程序的大量实例,最终导致后台工作人员锁定并一直报告忙碌。为了纠正这个问题,我需要输入

connection.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedEvent);

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

于 2012-10-04T13:00:32.450 回答