Last Updated: February 25, 2016
·
597
· daiakushi

Set/Unset polling thread in IronPython

In a Python console, you must release the thread resource or the thread will still run even the Form window is closed. A simple example is to uncomment the line self.add_FormClosing(self.EventOnClosing) and see what will happen. :)

import clr

clr.AddReference('System.Windows.Forms')

from System.Windows.Forms import *
from System.Threading import *

class Main(Form):
    def __init__(self):
        self.Counter = 0
        self.TimerThread = Timer(TimerCallback(self.ThreadCallBack), None, 0, 1000)
        self.add_FormClosing(self.EventOnClosing)

    def ThreadCallBack(self, o = None):
        self.Counter = self.Counter + 1
        print self.Counter

    def EventOnClosing(self, sender, e):
        self.TimerThread.Dispose()

def Run():
    Application.EnableVisualStyles()
    Application.Run(Main())