在处理时通过ironPython冻结创建的Gui表单

时间:2015-09-15 12:46:51

标签: c# ironpython python-multithreading

import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")

from System.Drawing import Point
from System.Windows.Forms import Application, Button, Form, Label

class HelloWorldForm(Form):

    def __init__(self):
        self.Text = 'writeLogInfo'

        self.label = Label()
        self.label.Text = "writeLogInfo"
        self.label.Location = Point(50, 50)
        self.label.Height = 30
        self.label.Width = 200

        self.count = 0

        button = Button()
        button.Text = "Click Me"
        button.Location = Point(50, 100)

        button.Click += self.buttonPressed

        self.Controls.Add(self.label)
        self.Controls.Add(button)

    def buttonPressed(self, sender, args):
        print 'The label *used to say* : %s' % self.label.Text
        self.count += 1
        self.label.Text = "You have clicked me %s times." % self.count  


        for i in range(100):
          host.WriteInfoOnPanel("Test : " + str(i))
          host.Pause(300)

form = HelloWorldForm()
Application.Run(form)

我已经准备了上面的IronPython脚本,它创建了gui,而for循环在主GUI上写了一些信息。

我的主要gui公开WriteInfoOnPanel函数并运行pythons脚本:

_scriptEngine = Python.CreateEngine();
_mainScope = _scriptEngine.CreateScope();

var scriptSource = scriptEngine.CreateScriptSourceFromFile(pathToScriptFile, Encoding.Default, SourceCodeKind.File);

_mainScope.SetVariable("host", _hostContract);
scriptSource.Execute(_mainScope);

不幸的是,当表单打开并且我点击按钮时它会冻结,直到循环结束。

有什么好的做法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

要在处理期间保持UI响应,任何长时间运行的任务都需要在后台线程上运行。使用ThreadPool.QueueUserWorkItemTask.Run之类的内容。如果后台线程需要更改UI,请使用Control.Invoke以确保正确处理这些更新(所有UI更新必须在创建它的线程上进行; Control.Invoke负责处理)。