IronPython/C#运行脚本后,我无法重新打开串行端口 [英] IronPython / C# I can't reopen a serial port after Script has been run

查看:141
本文介绍了IronPython/C#运行脚本后,我无法重新打开串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序"Mission Planner"允许运行python脚本以自定义程序的行为. 任务计划程序"在其自己的线程中运行脚本.当线程正在运行时,我可以选择按下任务计划器"中的调用"Thread.Abort()"的中止按钮.当我按下该按钮时,脚本中止,但是当我再次运行脚本时,这次我无法打开串行端口.我相信这是因为线程在关闭串行端口之前会中止.有没有一种方法来可靠地处理Thread.Abort()?还是在打开端口时处理此问题会更好?

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?

此处是 Mission Planner GitHub

此处是任务计划程序

下面是我的Python脚本.

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()

推荐答案

System.IO.Ports.SerialPort IDisposable 实现为释放分配的资源(在您的情况下为串行端口本身)的工具.使用 with语句作为IronPython的"rel =" nofollow noreferrer"> C#的using语句应该有助于释放Thread.Abort上的串行端口.

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.

这篇关于IronPython/C#运行脚本后,我无法重新打开串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆