I read that Timers.timer is a wrapper for the Threading.timer class. The timer should run on a workerthread of the threadpool. Yet in below example, the event isn't executed when the dialog is shown. I should guess that the form-thread and the worker thread are running independently and so the file would be filled with different values? Now they are the same because all fired events are executed just after the form is closed.
$timer = New-Object Timers.timer
$frm = New-Object System.Windows.Forms.Form
$timer.Interval = 2000
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {get-date -Format "ss" >> dezefile.txt}
$timer.Start()
$frm.ShowDialog()
$timer.stop()
$timer.Dispose()
The PowerShell engine can only process events registered for via Register-ObjectEvent
while it is in control of the foreground thread.
A .ShowDialog()
call puts WinForms in charge of the foreground thread, blocking PowerShell's event processing until after the form (dialog) is closed.
Solution options:
Use a System.Windows.Forms.Timer
instance instead, and subscribe to its Tick
event via an add_Tick()
call, and perform the desired processing inside the script block passed to the call.
Forgo a .ShowDialog()
call in favor of a non-blocking .Show()
call, which requires subsequently entering a loop with periodic [System.Windows.Forms.Application]::DoEvents()
calls.
See this answer for details.