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 に答える