Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在应用程序退出时正确终止线程_Python_.net_Multithreading_Winforms_Python.net - Fatal编程技术网

Python 如何在应用程序退出时正确终止线程

Python 如何在应用程序退出时正确终止线程,python,.net,multithreading,winforms,python.net,Python,.net,Multithreading,Winforms,Python.net,我正在使用pythonnet制作简单的gui import os, sys, ntpath, threading from subprocess import call import clr clr.AddReference("System") clr.AddReference("System.Windows.Forms") import System import System.Windows.Forms as WinForms from System.Threading import

我正在使用pythonnet制作简单的gui

import os, sys, ntpath, threading
from subprocess import call

import clr
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")


import System
import System.Windows.Forms as WinForms
from System.Threading import ApartmentState, Thread, ThreadStart
from System.Windows.Forms import (Application, Form, Button)
from System.Drawing import Point

class demo(WinForms.Form):
    def __init__(self):
        self.filename = None
        self.InitializeComponent()

    def InitializeComponent(self):
        """Initialize form components."""
        self.components = System.ComponentModel.Container()
        self.btn = Button()
        self.btn.Parent = self
        self.btn.Click += self.process
        self.CenterToScreen()
        self.cmd = "Running forever command"

    def Dispose(self):
        self.components.Dispose()
        WinForms.Form.Dispose(self)

    def thread_process(self):
        call(self.cmd, shell=True)
        pass

    def process(self, sender, args):
        self.thread = threading.Thread(target=self.thread_process, daemon=True)
        self.thread.start()

    def OnClickFileExit(self, sender, args):
        self.Close()

WinForms.Application.Run(demo())

它工作正常,但当我点击退出按钮时,应用程序显然不会停止。如何在用户关闭应用程序时正确停止正在运行的线程?

如果满足您的需要,您可能希望尝试将
进程
线程设置为
deamon
线程:

self.thread = threading.Thread(target=self.thread_process, daemon=True)
以下是有关deamon线程的一些信息:

线程可以标记为“守护线程”。这一点的意义 标志是当只有守护进程线程时,整个Python程序退出 剩下的就剩下了。初始值从创建线程继承。这个 可以通过daemon属性设置标志

资料来源:


已经有了。我认为问题在于subprocess.call启动了另一个非守护进程。但问题是在生成的程序是另一个python线程时开始的。所以这一切都混在一起了。这是铁蟒还是蟒蛇?