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

时间:2022-01-01 20:39:27
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)

I have prepared above IronPython script which creates gui and in for loop writes some info on main GUI.

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

My main gui exposes WriteInfoOnPanel function and runs pythons script:

我的主要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);

Unfortunately while form opens and I click button it freeze till for loop ends.

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

Are there any good practise how to cope with that?

有什么好的做法如何应对?

1 个解决方案

#1


1  

To keep the UI responsive during processing any long-running tasks need to be run on a background thread. Use something like ThreadPool.QueueUserWorkItem or Task.Run. If the background thread needs to change the UI, use Control.Invoke to ensure that those updates are properly handled (all UI updates must occur on the thread that created it; Control.Invoke takes care of that).

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

#1


1  

To keep the UI responsive during processing any long-running tasks need to be run on a background thread. Use something like ThreadPool.QueueUserWorkItem or Task.Run. If the background thread needs to change the UI, use Control.Invoke to ensure that those updates are properly handled (all UI updates must occur on the thread that created it; Control.Invoke takes care of that).

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