In reference to using PowerShell in VB or C# via System.Management.Automation
I know that Invoke runs synchronously, and using BeginInvoke / EndInvoke means you can do same thing asynchronously.
But I noticed today that there is also InvokeAsync
Can anyone explain to me the benefit of using this over the other methods and if there is a particular method I should be using?
Most examples I see use Invoke for basic commands and BeginInvoke / EndInvoke for longer running tasks.
Just want to learn best approach and have an understanding of what to use when as can't find much documentation on InvokeAsync like I could the others.
update: Quick examples below of same code using Invoke or BeginInvoke/EndInvoke
Thanks
Dim powershell As PowerShell = PowerShell.Create()
powershell.AddCommand("Get-Process")
Dim results = powershell.BeginInvoke
Do While results.IsCompleted = False
' wait whilst command completes
Loop
For Each result As PSObject In powershell.EndInvoke(results)
UpdateTextBox("Process Name: " & result.Members("ProcessName").Value & " Process ID: " & result.Members("Id").Value & vbCrLf)
Next result
or
Dim powershell As PowerShell = PowerShell.Create()
powershell.AddCommand("Get-Process")
Dim results = powershell.Invoke
For Each result As PSObject In results
UpdateTextBox("Process Name: " & result.Members("ProcessName").Value & " Process ID: " & result.Members("Id").Value & vbCrLf)
Next result
If you're using the TPL throughout your app then use InvokeAsync
. You can await the call or not, just as you can for any other async method.
If you need an invocation to be synchronous, eg your background operation has to wait to get input from the UI, then use Invoke
.
If you don't need an invocation to be synchronous then use BeginInvoke
. If you need to get data back then use EndInvoke
as well. For instance, if you are performing an operation in the background and updating a ProgressBar
, you should call BeginInvoke
rather than Invoke
. That's because there's no need for the background work to wait while the that update happens. You don't need any result though, so there's no need to call EndInvoke
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.