Reputation: 14064
I'm trying to call an async method on a .Net object instantiated in Powershell :
Add-Type -Path 'my.dll'
$myobj = new-object mynamespace.MyObj()
$res = $myobj.MyAsyncMethod("arg").Result
Write-Host "Result : " $res
When executing the script, the shell doesn't seem to wait for MyAsyncMethod().Result
and displays nothing, although inspecting the return value indicates it is the correct type (Task<T>
). Various other attempts, such as intermediary variables, Wait()
, etc. gave no results.
Most of the stuff I found on the web is about asynchronously calling a Powershell script from C#. I want the reverse, but nobody seems to be interested in doing that. Is that even possible and if not, why ?
Upvotes: 16
Views: 11324
Reputation: 5817
For long running methods, use the PSRunspacedDelegate
module, which will enable you to run the task asynchronously:
$task = $myobj.MyAsyncMethod("arg");
$continuation = New-RunspacedDelegate ( [Action[System.Threading.Tasks.Task[object]]] {
param($t)
# do something with $t.Result here
} );
$task.ContinueWith($continuation);
See documentation on GitHub. (Disclaimer: I wrote it).
Upvotes: 5
Reputation: 7518
I know this is a very old thread, but it might be that you were actually getting an error from the async method but it was being swallowed because you were using .Result
.
Try using .GetAwaiter().GetResult()
instead of .Result
and that will cause any exceptions to be bubbled up.
Upvotes: 15
Reputation: 6738
This works for me.
Add-Type -AssemblyName 'System.Net.Http'
$myobj = new-object System.Net.Http.HttpClient
$res = $myobj.GetStringAsync("https://google.com").Result
Write-Host "Result : " $res
Perhaps check that PowerShell is configured to use .NET 4:
How can I run PowerShell with the .NET 4 runtime?
Upvotes: 4