嵌入式IronPython - 调度程序问题

时间:2011-06-06 13:51:10

标签: multithreading ironpython dispatcher

我试图隐瞒IP in Action附带的一些代码,在发布问题之后,我甚至不厌其烦地阅读这本书!

当我使用以下代码时,我收到错误'expect Delegate,got Function'。仅供参考我传递WPF文本框的引用,所以我应该在我的UI元素上有一个调度程序

我删除了所有的线程管道读取内容只是为了留下'test'代码:

import System
import System.IO
import Avacta.Optim.Server.WebServices
import Avacta.Optim.Server.DataModel
import sys
import clr
import time

from System import Console
from System.Threading import Thread, ThreadStart

def SetDispatcher(ui_element):
    global dispatcher # needed else "Exception: 'NoneType' object has no attribute 'BeginInvoke'"
    dispatcher = ui_element.Dispatcher 

def Dispatch(function, *args):
    dispatcher.BeginInvoke(lambda *_: function(*args))

def GetDispatchFunction(function):
    return lambda *args: Dispatch(function, *args)

class ListOutput:
    def __init__(self, textbox):
    self.textbox = textbox

def write(self, string):
    Dispatch(self.addText, string) # error: "expect Delegate, got Function"
    #self.addText(string) # ok works fine w-w/o dispatcher stuff

def addText(self, string):
    textbox.AppendText(string)

if textbox != None:
    listout = ListOutput(textbox)
    sys.stdout = listout
    SetDispatcher(textbox)

print "Define running"
#running = True

Thread.Sleep(0)
time.sleep(2)

print "Start The Comms Thread..."
#comms_t = Thread(ThreadStart(run_comms))
#comms_t.Start()

Thread.Sleep(0)
time.sleep(2)

任何线索都表示赞赏。

AndyF。

2 个答案:

答案 0 :(得分:1)

感谢Dino Viehland

更改我的调度程序代码以直接调用调度程序可以解决此问题。

dispatcher.BeginInvoke(System.Action(lambda *_: function(*args)))

不幸的是,我不再从我的打印状态获得实时输出到我的'控制台' - 这一切都在脚本完成时出现。删除调度程序,它将恢复为实时...

答案 1 :(得分:0)

通过DispatcherExtensions提供了一组调度程序静态方法(扩展方法),它以Action作为参数。

下面的代码示例演示了WPF调度程序的用法。有关详细信息,请访问http://msdn.microsoft.com/en-us/library/cc647497.aspx

import clr
clr.AddReference('WindowsBase')
clr.AddReference('System.Windows.Presentation')
from System import Action
from System.Windows.Threading import DispatcherExtensions, Dispatcher

dispatcher = Dispatcher.CurrentDispatcher

def workCallBack():
    print 'working'

DispatcherExtensions.BeginInvoke(dispatcher, Action(workCallBack))