Question

The program "Mission Planner" allows python scripts to be ran in order to customize the behavior of the program. The "Mission Planner" runs the script in its own thread. When the thread is running I have the option to press the abort button which calls "Thread.Abort()" within "Mission Planner". When I press this button the script aborts but when I run the script again I cannot open the serial port this time. I believe it is because the thread aborts before closing the serial port. Is there a way to robustly handle a Thread.Abort()? Or would it be better to handle this issue when I open the port?

Here is a link to the Mission Planner GitHub

Here is a link to the Mission Planner Program

Below is my Python script.

Note: This is simplified version of my script that demonstrates my problem. My script is intended to run in the background until it is aborted.

import clr
clr.AddReference('System')
from System import *

serialPort = IO.Ports.SerialPort("COM3")
serialPort.BaudRate = 9600
serialPort.DataBits = 8
serialPort.Open()

while 1:
    print serialPort.ReadLine()

serialPort.Close()
Was it helpful?

Solution

System.IO.Ports.SerialPort implements IDisposable as a facility for freeing allocated resources (in your case the serial port itself). Using the with statement as the IronPython equivalent of C#'s using statement should help free the serial port on Thread.Abort.

The script could be changed the following way:

import clr
clr.AddReference('System')
from System import *

with IO.Ports.SerialPort("COM3") as serialPort:
    serialPort.BaudRate = 9600
    serialPort.DataBits = 8
    serialPort.Open()

    while 1:
        print serialPort.ReadLine()

Side-note (even though it is most likely out of your control): Aborting a thread is often considered as a bad practice (see for example the many questions around this topic) as it is not a safe way to handle external/untrusted/performance-hugging code because it does not guarantee abortion of the thread or provide proper isolation (compared to using app domains + policies). As you already experienced it is also inconvenient for the executed thread body/code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top