[英]Register-ObjectEvent from runspace
I have a Barcode scanning script. 我有一个条形码扫描脚本。 it opens the RS323 Port to the handheld scanner register-objects event on "DataReceived" runs an action Scriptblock to update database fields.
它会打开“ DataReceived”上的手持扫描器注册对象事件的RS323端口,并运行一个脚本块以更新数据库字段。
this all works when running normally (from mainthread) but now i would like to do the same from a runspace and return the barcode to the mainthread. 这一切都正常运行时(从主线程),但是现在我想从运行空间执行相同操作,并将条形码返回到主线程。 this way i would not block the running thread.
这样我就不会阻塞正在运行的线程。
$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()
You can use a synchronized hash table to store the Result data, which would allow you to see the data from the parent runspace 您可以使用同步的哈希表存储结果数据,这将使您可以从父运行空间查看数据
$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()
You can then access the result using $syncHash.Result
然后,您可以使用
$syncHash.Result
访问结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.