Problem with events when useing Start-job and WPF

This topic contains 3 replies, has 2 voices, and was last updated by  Martin Nielsen 3 years, 11 months ago.

  • Author
  • #17455

    Niklas Gustafsson

    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?


    $syncHash = [hashtable]::Synchronized(@{})
    $newRunspace =[runspacefactory]::CreateRunspace()
    $newRunspace.ApartmentState = "STA"
    $newRunspace.ThreadOptions = "ReuseThread"          
    $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
                $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.

  • #17471

    Martin Nielsen

    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?

  • #17477

    Niklas Gustafsson

    Yes, of course 🙂

  • #17481

    Martin Nielsen

    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.

You must be logged in to reply to this topic.