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

How to terminate Correctly thread on application exit

我正在使用 pythonnet 制作简单的图形用户界面。

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

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

如果适合您的需要,您可能想尝试将 process 线程设置为 deamon 线程:

self.thread = threading.Thread(target=self.thread_process, daemon=True)

这里有一些关于守护线程的信息:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

Source: https://docs.python.org/2/library/threading.html#thread-objects