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

标签 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 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

关于python - 如何在应用程序退出时正确终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365127/

相关文章:

java - 如何在不同的应用程序级别锁定文件?

python - 就速度和内存而言,迭代非常大的循环并将 scipy 稀疏矩阵存储到文件中的最有效方法

python - 错误 : "MSVCP90.dll: No such file or directory" even though Microsoft Visual C++ 2008 Redistributable Package is installed

c# - 如何使用 ionic 库压缩文件

c# - System.Configuration 的线程安全使用

java - 如何在主线程上围绕 java 中的某些代码设置超时?

python - Django 从没有外键关系的多个表中检索数据

python - 访问主题的内容

.net - 周转基金。 REST 架构。如何在 JSON (POST) 中从客户端获取对象

.net - 需要 JavaScript 代码方面的帮助