Multithreading and Serial Ports Multithreading and Serial Ports multithreading multithreading

Multithreading and Serial Ports


I think you need something like this. Don't know if the locks are needed but I added them for safety since you are getting errors

private void SensorThread_DoWork(object sender, DoWorkEventArgs e) {    int sensor = 1;    while(!SensorThread.CancellationPending == true)     {        int newSensor;        lock(this)        {            newSensor = ReadSensor();         }        //sensor state changed        if(newSensor != sensor)        {            //sensor was 1 and changed to 0            if(newSensor==0)            {               scaleTimer.Start();             }            sensor = newSensor;        }        Thread.Sleep(1);    }    e.Cancel = true; }     private void ScaleThread_DoWork(object sender, DoWorkEventArgs e) {     //sensor blocked     //if (sensorstatus == 0)     {         lock(this)        {            ReadScale();         }        //SaveWeight();         prevgate = gate;         gate = DetermineGate();         lock(this)        {            SetOpenDelay();             SetDuration();         }      //if gate = 0, this means the weight of meat on scale        //is not in any weight range. Meat runs off the end.       if (gate == 0)       {         txtStatus.Invoke(new UpdateStatusCallback(UpdateStatus), new object[] { meatweight.ToString() +                                                                              "lbs is out of range"});       }       else       {         lock(this)        {        //open gate         }        lock(this)        {        //close gate         }      }   } 


I would suggest that your best bet is probably to create a dedicated thread to sit on each serial port. Such an approach will neither require, nor forbid, any similarity in how the ports are handled, will avoid any interference in operation between the ports, and will be scalable within reasonable bounds (using a thread for each of 32 ports would be fine; using a thread for each of 1,000 would be bad). Although one should avoid creating threads which will simply run for a short time and quit, or creating really huge numbers of threads, using a dedicated thread for each serial port will ensure that when data comes in there will be a thread ready to handle it.


I notice that you don't have any loops in your thread's DoWork methods. That would be a great place to start. The worker thread should be a loop that doesn't return until CancellationPending is set to true. They won't loop on their own just because you have it in a thread -- the thread will run until it is done, then exit.

Edited to add: What you seem to be missing is that you need to split up the code that monitors the scale and the code that opens and closes the gate. One way to do that would be to have an infinite loop that monitors the scale, and when it detects something, it starts a new thread that handles opening and closing the gate.