Как обернуть блокирующий метод в асинхронную задачу - PullRequest
0 голосов
/ 19 июня 2019

Вот небольшой фрагмент кода , блокирующего код , который я хочу сделать асинхронным .Он просто ждет моего ввода и затем выводит его на экран, когда я нажимаю 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()<---
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...