Problem with events when useing Start-job and WPF

Hello,
I have been trying to get “start-job” to work with WPF and events, but all it dose is crashing when the event is fired. I am guessing that it has something to do with the run-spaces, but cant figure out how to solve it. It works perfectly fine with windows forms. Do any of you have some ideas?

CODE:

$syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"          
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)          
$psCmd = [PowerShell]::Create().AddScript({   
    [xml]$xaml = @"
    
        
    
"@
 
    $reader=(New-Object System.Xml.XmlNodeReader $xaml)
    $syncHash.Window=[Windows.Markup.XamlReader]::Load( $reader )
    $syncHash.TextBox = $syncHash.window.FindName("textbox")
    $syncHash.Window.ShowDialog() | Out-Null
    $syncHash.Error = $Error


})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()

$job = Start-Job -Name "ReturnMessage" -ScriptBlock {
        # forward events named "MyNewMessage" back to job owner
        # this even works across machines
        Register-EngineEvent -SourceIdentifier MyNewMessage -Forward

        while($true) {
            sleep 2
            $i++
            $message = "This is message $i."
            # raise a new progress event, assigning to $null to prevent
            # it ending up in the job's output stream
            $null = New-Event -SourceIdentifier MyNewMessage -MessageData $message
        }
}

$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {
    $syncHash.Window.Dispatcher.invoke([action]{$syncHash.TextBox.Text($message)}, "Normal")
}

EDIT Apparently I cant type any xaml code.

I’d love to play around with it, but I have to admit writing XAML isn’t exactly one of my strong skills.

Any chance you can post the missing piece on a pastebin service, or attach the script file to your post?

Yes, of course :slight_smile:

Well I’m stumped. The best I can say is if I run

$synchash.window.Dispatcher.Invoke({ $synchash.TextBox.Text = 'test' })

it updates the TextBox property correctly, but getting an event to do it seems troublesome. It wouldn’t surprise me if it has something to do with an event in one thread trying to access and modify data in another thread.

I’m afraid the only ideas I have at this point involve using C#, and that’s no fun.