TOP KEK
TOP KEK

Reputation: 2651

Using AsyncCallback in Powershell

I have to call a method on .NET object which is defined as

IAsyncResult BeginListMetrics( ListMetricsRequest listMetricsRequest, AsyncCallback callback, Object state )

Is it possible to use a powershell function as a AsyncCallback delegate? How?

Upvotes: 4

Views: 6149

Answers (2)

jimhark
jimhark

Reputation: 5046

While @Xpw's answer is correct and casting Scriptblocks into delegates is generally useful, for the specific case of AsyncCallback, more is usually required.

Oisin Grehan's PowerShell 2.0 – Asynchronous Callbacks from .NET explains the problem and provides a solution. A fully worked example is available. While Oisin makes the problem clear, his solution will be hard to understand if you're not familiar with Register-Objectevent.

For full details see Oisin's great write-up. Briefly, an AsyncCallback is called via the Thread Pool and so will not be able to run a ScriptBlock because the thread doesn't have a PowerShell RunSpace. The workaround is to embed a small C# class that takes the AsyncCallback and raises an event, while Register-ObjectEvent is used to setup an event handler in PowerShell.

Upvotes: 2

Χpẘ
Χpẘ

Reputation: 3451

Scriptblocks can be converted into most types of delegates by casting as follows.

$myCallback = [AsyncCallback]{
  param( $asyncResult)
  # callback code
  if ($asyncResult.isCompleted) {
    get-date
  }
}

Upvotes: 8

Related Questions