0

Is there a Python's equivalent of C#'s SynchronizationContext?

I'm developing an application where I have two threads, the UI thread (that needs to be the main thread) and the Logic thread. The objects for them to be used in the UI they must be created in the UI thread.. The problem is that when the UI is shown, the UI thread gets "stuck" in a blocking call from the lib I'm using

I'm looking for a way to create an object in the UI thread from the Logic thread

StackOverfow about SynchronizationContext

What doesn't work:

import threading

class LogicThread(threading.Thread):
    def __init__(self, mw):
        threading.Thread.__init__(self)
        self.mw = mw
        self.daemon = True


    def run(self):
        self.wdc = WindowDataContext() # ok, no problem

        self.mw.DataContext = self.wdc # Doesn't work, object must 
                                       # be created in UI thread


mw = MainWindow()

t = LogicThread(mw)
t.start()

app.Run(mw) # blocking call

What I have now that is working:

import threading

class LogicThread(threading.Thread):
    def __init__(self, wdc):
        threading.Thread.__init__(self)
        self.wdc = wdc
        self.daemon = True


    def run(self):
        i = 0
        while True:
            self.wdc.Text = str(i) # no problem
            print(i)
            i += 1
            time.sleep(0.5)


wdc = WindowDataContext()
mw = MainWindow()
mw.DataContext = wdc

t = LogicThread(wdc)
t.start()

app.Run(mw) # blocking call
Victor Marcelino
  • 219
  • 3
  • 10
  • Just so I can reproduce your problem: what UI lib are you using? – digitalarbeiter Nov 08 '18 at 20:46
  • @digitalarbeiter I'm using a wpf dll and pythonnet to access it. Full source code is available [Here](https://github.com/vMarcelino/KeyChainer/blob/master/KeyChainer.Core/ui_spawner.py) – Victor Marcelino Nov 08 '18 at 21:13
  • I'm really sorry but I've got no Windows system, and I suspect very strongly this is Windows-specific behaviour. I'm not aware of thread-specific object ownership under Linux Python. (If anyone out there _is_ aware, please enlighten me.) – digitalarbeiter Nov 08 '18 at 21:32

0 Answers0