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并在主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);
不幸的是,当表单打开并且我单击按钮时,它会冻结直到循环结束。
有什么好的做法可以应对吗?
为了在处理过程中保持 UI 的响应,任何长时间运行的任务都需要在后台线程上运行。使用类似 ThreadPool.QueueUserWorkItem
或 Task.Run
.如果后台线程需要更改 UI,请使用 Control.Invoke
确保正确处理这些更新(所有 UI 更新都必须在创建它的线程上进行; Control.Invoke
负责(。