powershell - 如何将阻塞方法包装到异步任务中
问题描述
这是我想要制作的一小段阻塞代码asynchronous。它只是等待我的输入,然后在我按下 时将其输出到屏幕enter
。
while ($true) {
$result = [Console]::In.ReadLine()
"RESULT: $result"
}
在这里,我试图将此阻塞方法包装[Console]::In.ReadLine()
到返回 a 的函数中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()<---
解决方案
推荐阅读
- r - 如何使计数图中的所有行都从对照组开始
- python - 在 Pandas 中展平包含 JSON 数组的列
- sql-server - 对日期使用 ID 进行挑选 - lastWeekEnd 和 lastMonthEnd 是同一日期时的问题
- java - How to implement builder inside my already defined class
- c# - 为什么 Aurio 无法比较我的音轨?
- javascript - 更改变量的属性时触发事件
- html - HTML 页面不滚动
- javascript - 用数字和字符分隔字符串
- symfony - 如何在序列化过程中禁用所有相关实体的自动加载?
- multithreading - Clojure 并行计算数组