Python等价于C的SynchronizationContex

2024-03-29 14:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

有Python的C#SynchronizationContext等价物吗?你知道吗

我正在开发一个应用程序,其中我有两个线程,UI线程(需要是主线程)和逻辑线程。要在UI中使用的对象必须在UI线程中创建。。问题是,当显示UI时,UI线程“卡住”在来自我使用的lib的阻塞调用中

我正在寻找一种方法,从逻辑线程在UI线程中创建一个对象

关于SynchronizationContext的叠加

什么不起作用:

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

我现在的工作是:

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

Tags: 对象importselftrueuiinitdef逻辑