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

Gui form created via ironPython freeze while processing

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)

我在上面准备了创建 gui 的 IronPython 脚本,并在 for 循环中在主 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);

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

有什么好的做法可以应对吗?

要在处理任何长运行宁任务期间保持UI响应,需要在后台线程上运行。使用 ThreadPool.QueueUserWorkItem or Task.Run. If the background thread needs to change the UI, use Control.Invoke 之类的东西来确保正确处理这些更新(所有 UI 更新必须发生在创建它的线程上;Control.Invoke 负责)。