1
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.

My main gui exposes WriteInfoOnPanel function and runs pythons script:

_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?

komizo
  • 1,052
  • 14
  • 21

1 Answers1

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).

Jeff Hardy
  • 7,632
  • 24
  • 24
  • thanks, I managed to to that by Task which is started from C# and exposed to python, I knew that it is also possible to use C# Thread directly from ironPython – komizo Sep 22 '15 at 12:11