更新:
在阅读了您的评论并更仔细地阅读了您的问题之后,我认为您可能正在寻求利用异步事件处理。下面是一个监听事件直到超时然后退出的示例。此示例假定您可以更改程序集以添加事件。
生成事件的类:
namespace ClassLibrary1
{
public class Class1
{
public event EventHandler SomeEvent;
protected void OnSomeEvent(EventArgs e)
{
var someEvent = SomeEvent;
if (someEvent != null)
{
SomeEvent(this, e);
}
}
public void SomeMethod()
{
Task.Run(() =>
{
for (int i = 0; i < 3; i++)
{
Thread.Sleep(3000);
OnSomeEvent(EventArgs.Empty);
}
});
}
}
}
电源外壳:
# Load up your .net assembly
add-type -path .\Class1.cs
$x = new-object ClassLibrary1.Class1
$sourceIdentifier = "SomeEvent"
# Register event
$eh = Register-ObjectEvent -SourceIdentifier $sourceIdentifier -InputObject $x -EventName SomeEvent
$x.SomeMethod()
while ($true)
{
Write-Host "Waiting for event..."
$event = Wait-Event -SourceIdentifier $sourceIdentifier -Timeout 10
if ($event -eq $null)
{
Write-Host "No event received for 10 seconds."
break
}
# Do processing here
Write-Host "Processing event..."
$event
# Remove event from queue
Remove-Event -SourceIdentifier $sourceIdentifier
}
Unregister-Event -SourceIdentifier $sourceIdentifier
Write-Host "Done processing events."