resu101 resu101 -4 years ago 142 Question

Need a way to execute a powershell script asynchronosly

On a Windows 7 PC, I'm building a Windows Forms application with

  • Visual Studio 2015 Enterprise


  • .Net Framework 4.5.2

  • PowerShell 5.0

The application involves multithreading because it has an embedded PowerShell script that takes a fairly long time to run. Embedded here means that the
function (shown below) builds a string variable with the PowerShell script text. A second thread runs
and the main thread places the returned data from this function on a main form control. I first used the BackgroundWorker approach, with the DoWork handler, etc. This works perfectly. Then I read about the newer async / await approach; I rebuilt everything using async / await and I hit a wall. This sample

Imports System.Management.Automation

Public Class demo

Private Async Sub form_Load(sender As Object, e As EventArgs) Handles MyBase.Load

' Some statements

Dim listOfStringVar As List(Of String) = Await fillListOfStringVarAsync()

' Some statements that use the
' listOfStringVar
' value

End Sub

Private Async Function fillListOfStringVarAsync() As Task(Of List(Of String))

Dim scriptText As String = "#PowerShell 5.0 script, known to work"
Dim stringListVar As New List(Of String)

Dim psInstance As PowerShell = PowerShell.Create().AddScript(scriptText)
Dim async As IAsyncResult = psInstance.BeginInvoke() 'await won't work here

For Each obj As PSObject In psInstance.EndInvoke(async) 'await won't work here



Return stringListVar

End Function

End Class

shows the basic engineering of the rebuild, with async / await. The problem: inside the
function, the psInstance object - which has the PowerShell script - needs an await expression, but I don't know the correct syntax for this. Visual Studio green-underlines the function name
with a warning that

This async method lacks 'Await' operators and so will run asynchronously etc. etc. etc.

The app compiles, but without the await operator in
, the main form disappears until the secondary thread completes and returns its data. This page and this page, both from Microsoft, brought me the closest. I looked all over StackOverflow but no luck.

Answer Source

You can use await Task.Run(() => YourMethod());

I'm not sure that will help though. At least in web apps, awaiting will still stop your form from showing up until the async method has completed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download