Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting result of .Net object asynchronous method in powershell

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 ?

like image 788
guillaume31 Avatar asked Sep 15 '14 15:09

guillaume31


Video Answer


3 Answers

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.

like image 163
Mike Goatly Avatar answered Oct 11 '22 06:10

Mike Goatly


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).

like image 28
Tahir Hassan Avatar answered Oct 11 '22 05:10

Tahir Hassan


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?

like image 25
What Would Be Cool Avatar answered Oct 11 '22 06:10

What Would Be Cool