2017-02-21 14 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

あなたはそれがあなたの必要性に合っている場合deamonスレッドとしてあなたprocessスレッドを設定しようとする場合があります:スレッドのようにフラグを立てることができ

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

はここでデーモンスレッドでいくつかの情報です"デーモンスレッド"。この フラグの意味は、デーモンスレッド だけが残っていると、Pythonプログラム全体が終了するということです。初期値は作成スレッドから継承されます。 フラグは、daemonプロパティで設定できます。

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

+0

既にしました。私は問題が別の非デーモンを起動するsubprocess.callだと思う。 – Rahul

+0

解決済み。しかし、問題は、結果のプログラムが別のpythonスレッドだったときに始まりました。だからそれはすべて混ざった。 – Rahul

関連する問題