2017-02-21 110 views
1

我正在使用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()) 

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

+0

这是IronPython的或pythonnet? – denfromufa

回答

2

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

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

这里的守护进程线程的一些信息:

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

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

+0

已经做到了。我认为问题是启动另一个非守护进程的subprocess.call。 – Rahul

+0

解决。但是,当产生的程序是另一个python线程时,问题就开始了。所以它混合起来。 – Rahul