这里有一小段 blocking 代码,我想使其异步。它只是等待我的输入,然后在我按enter
时将其输出到屏幕。
while ($true) {
$result = [Console]::In.ReadLine()
"RESULT: $result"
}
在这里,我正在尝试将此阻塞方法[Console]::In.ReadLine()
包装到一个返回task
的函数中,但是result
属性始终为空。我想念什么?
function readConsoleWrapper {
$action = [Action]{
[Console]::In.ReadLine()
}
New-Object System.Threading.Tasks.Task($action)
}
$readLineTask = readConsoleWrapper
while ($true) {
sleep -s 1
$result = $readLineTask.result
"RESULT: $result"
}
现在,我添加了$readLineTask.start()
和Write $readLineTask
行,这是错误的
Exception : System.AggregateException: One or more errors occurred. --->
System.Management.Automation.PSInvalidOperationException: There is no Runspace available to
run scripts in this thread. You can provide one in the DefaultRunspace property of the
System.Management.Automation.Runspaces.Runspace type. The script block you attempted to
invoke was:
[Console]::In.ReadLine()
at System.Management.Automation.ScriptBlock.GetContextFromTLS()
at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder,
Object dollarThis, Object[] args)
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.Management.Automation.PSInvalidOperationException: There is
no Runspace available to run scripts in this thread. You can provide one in the
DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The
script block you attempted to invoke was:
[Console]::In.ReadLine()
at System.Management.Automation.ScriptBlock.GetContextFromTLS()
at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder,
Object dollarThis, Object[] args)
at System.Threading.Tasks.Task.Execute()<---