4

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?

2 Answers 2

8

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

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.