我有一个条形码扫描脚本。 它会打开手持扫描仪的RS323端口 “ DataReceived”上的注册对象事件 运行动作脚本块以更新数据库字段。
这一切都正常运行时(从主线程运行),但是现在我想从运行空间执行相同操作,并将条形码返回到主线程。这样我就不会阻塞正在运行的线程。
$bcHandler =[runspacefactory]::CreateRunspace()
# set Single Threaded Apartment and reuse thread
$bcHandler.ApartmentState = "STA"
$bcHandler.ThreadOptions = "ReuseThread"
# Open the runspace
$bcHandler.Open()
$psCmd = [PowerShell]::Create().AddScript({
Param($ComPort="COM3")
$port= new-Object System.IO.Ports.SerialPort $ComPort,9600,None,8,one
Register-ObjectEvent -InputObject $port -EventName "DataReceived" -SourceIdentifier $port.PortName -Action {
# start stopwatch for perforance measurements
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
# Read scanner buffer
$Result = ($port.ReadExisting() | Out-String).Trim()
# Send beep to handheld scanner
$port.Write([char]7,0,1)
}
})
# Open the runspace
$psCmd.Runspace = $bcHandler
$Handler = $psCmd.BeginInvoke()
答案 0 :(得分:0)
您可以使用同步哈希表存储结果数据,这将使您可以从父运行空间查看数据
$Global:syncHash = [hashtable]::Synchronized(@{})
$bcHandler =[runspacefactory]::CreateRunspace()
# set Single Threaded Apartment and reuse thread
$bcHandler.ApartmentState = "STA"
$bcHandler.ThreadOptions = "ReuseThread"
# Open the runspace
$bcHandler.Open()
#Synch the HashTable between runspaces
$bcHandler.SessionStateProxy.SetVariable("syncHash", $syncHash)
$psCmd = [PowerShell]::Create().AddScript({
Param($ComPort="COM3")
$port= new-Object System.IO.Ports.SerialPort $ComPort,9600,None,8,one
Register-ObjectEvent -InputObject $port -EventName "DataReceived" -SourceIdentifier $port.PortName -Action {
# start stopwatch for perforance measurements
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
# Read scanner buffer
$syncHash.Result = ($port.ReadExisting() | Out-String).Trim()
# Send beep to handheld scanner
$port.Write([char]7,0,1)
}
})
# Open the runspace
$psCmd.Runspace = $bcHandler
$Handler = $psCmd.BeginInvoke()
然后您可以使用$syncHash.Result