首页 > 解决方案 > 如何将阻塞方法包装到异步任务中

问题描述

这是我想要制作的一小段阻塞代码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()<---

标签: powershell

解决方案


推荐阅读