C#BackgroundWorker和Com端口问题

CSh*_*Dev 3 c# multithreading modbus backgroundworker

好.我有一个监控2个COM端口的程序.一个连接到秤,另一个连接到modbus板.

我的问题是连接到modbus板的COM端口.我的程序每100MS读取一个传感器(在modbus板上).它返回0或1(通过COM端口)以确定传感器是否被阻塞.如果它被阻止,则通过端口向板发送信号.

我的问题是我无法退出监控传感器,但在发送其他信号之前我必须确保com端口未被使用.

监视传感器的例程在后台工作线程上.一旦传感器跳闸,产生另一个线程,向Modbus板发送信号.所以当我向电路板发送信号时,我需要暂停"传感器线程".我该怎么做呢?

请记住它是BackgroundWorker,因此Thread.Join不是一个选项.

这是我的代码:

private void SensorThread_DoWork(object sender, DoWorkEventArgs e)
    {
        if (SensorThread.CancellationPending == true)
            e.Cancel = true;
        else
        {
            ReadSensor();
        }    
    }
Run Code Online (Sandbox Code Playgroud)

此线程的RunWorkerCompleted只是重新启动线程.以下线程持续监视"sensorstatus"以查看传感器何时被阻塞:

public void ScaleThread_DoWork(object sender, DoWorkEventArgs e)
    {
        if (ScaleThread.CancellationPending == true)
        {
            e.Cancel = true;
        }
        else
        {
            //sensor is blocked
            if (sensorstatus == 0)
            {
                ReadScale();
                prevgate = gate;
                gate = DetermineGate();
                //SaveData();
                SetOpenDelay();
                SetDuration();
                //no gate was selected, meat out of range, runs off end
                if (gate == 0)
                {
                    txtStatus.Invoke(new UpdateStatusCallback(UpdateStatus), new object[] { meatweight.ToString() + 
                                                                                    "lbs is out of range"});
                }
                else
                {
                    //this triggers a thread to send a signal to the modbus board
                    gateTimer.Start();
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

RunWorkerCompleted为此重新启动此线程,使其成为循环

Ian*_*cer 5

创建一个负责所有发送操作的线程.实现一个Queue,为该线程提供消息以发送到设备.您可以使用new BlockingCollection<T>来轻松实现此功能.

或者,使用TPL,创建一个TaskScheduler有限度的并行度为1,如下所示: - http://msdn.microsoft.com/en-us/library/ee789351.aspx

现在您只需激活任务即可发送到设备,它们将按顺序执行.

除非需要在发送者和阅读器之间传递信息,否则我将在其自己的单独线程上实现阅读器操作.