Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Example, GUI app that freezes
- [void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
- $Form = [System.Windows.Forms.Form] @{
- Text = 'My GUI Window'
- }
- $ListBox = [System.Windows.Forms.ListBox] @{
- Dock = [System.Windows.Forms.DockStyle]::Fill
- }
- $Button = [System.Windows.Forms.Button] @{
- Text = 'Do something'
- Dock = [System.Windows.Forms.DockStyle]::Bottom
- }
- $Button.Add_Click(
- {
- $ListBox.Items.Insert(0, ('{0}: Do something' -f [Datetime]::Now))
- [System.Threading.Thread]::Sleep(5000)
- $ListBox.Items.Insert(0, ('{0}: Do something again' -f [Datetime]::Now))
- }
- )
- [void] $Form.Controls.AddRange(@($ListBox, $Button))
- [void] $Form.ShowDialog()
- # Example how to resolve the freeze issue with the same app
- $Sync = [HashTable]::Synchronized(@{})
- $Sync.Actions = [System.Collections.Queue]::new()
- $PowerShell = [PowerShell]::Create()
- $PowerShell.Runspace = [RunspaceFactory]::CreateRunspace()
- $PowerShell.Runspace.Open()
- $PowerShell.Runspace.SessionStateProxy.SetVariable('Sync', $Sync)
- # Run the GUI in a separate thread, that we dont freeze on user actions
- $Handle = $PowerShell.AddScript(
- {
- [void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
- $Sync.Form = [System.Windows.Forms.Form] @{
- Text = 'My GUI Window'
- }
- $Sync.ListBox = [System.Windows.Forms.ListBox] @{
- Dock = [System.Windows.Forms.DockStyle]::Fill
- }
- $Button = [System.Windows.Forms.Button] @{
- Text = 'Do something'
- Dock = [System.Windows.Forms.DockStyle]::Bottom
- }
- $Button.Add_Click(
- {
- $Sync.Actions.Enqueue('Do something')
- }
- )
- [void] $Sync.Form.Controls.AddRange(@($Sync.ListBox, $Button))
- [void] $Sync.Form.ShowDialog()
- }
- ).BeginInvoke()
- # While the handle of the separate thread we created is still running
- While (!$Handle.IsCompleted) {
- While ($Sync.Actions.Count -gt 0) {
- # Manage the actions we queue from inside
- Switch ($Sync.Actions.Dequeue()) {
- 'Do something' {
- $Sync.ListBox.Items.Insert(0, ('{0}: Do something' -f [Datetime]::Now))
- [System.Threading.Thread]::Sleep(5000)
- $Sync.ListBox.Items.Insert(0, ('{0}: Do something again' -f [Datetime]::Now))
- }
- }
- }
- [System.Threading.Thread]::Sleep(100)
- }
Advertisement
Add Comment
Please, Sign In to add comment