5

could you tell a beginner why this small WPF-application is not closing as intended after the WorkflowTerminated event fires? The used workflow just terminates immediately. (using a WPF application, .Net Framework 3.5)

public partial class MainWindow : Window
{
    private WorkflowRuntime wfRuntime = new WorkflowRuntime();

    public MainWindow()
    {
        InitializeComponent();

        wfRuntime.WorkflowTerminated += (se, ev) => this.Close(); // this doesn't close the window
        wfRuntime.WorkflowCompleted += (se, ev) => this.Close();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WorkflowInstance launcherWorkflow = wfRuntime.CreateWorkflow(typeof(InstallerWorkflow));

        launcherWorkflow.Start();
    }
}
nabulke
  • 11,025
  • 13
  • 65
  • 114

1 Answers1

6

Probably because the callback is on another thread. A basic workaround is to terminate the application altogether using Environment.Exit(1);

To call the close function on the UI thread you should use:

wfRuntime.WorkflowTerminated += (se, ev) => {
    // call back to the window to do the UI-manipulation
    this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() 
    {
       this.Close();
    }));
};
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • My Application object doesn't have an exit() method. Propably because it is an WPF application? I tried Application.Current.Shutdown() which doesn't help. Still doesn't close... – nabulke Apr 14 '11 at 07:35
  • How could I post the terminate event to the right thread (GUI thread)? – nabulke Apr 14 '11 at 07:37
  • Environment.Exit() works, the application is closing. But it feels kind of dirty ;-) Is there a cleaner way, to reach my goal (i.e. handling the event in the right thread, so Close() works as intended?). Nevertheless thanks for your help so far! – nabulke Apr 14 '11 at 07:40
  • 2
    Yep I updated the answer to callback the Close() method on the UI thread so UI windows closes right. – Teoman Soygul Apr 14 '11 at 07:41
  • Just fixed a typo by the way (forgot the second closing parenthesis before semicolon) – Teoman Soygul Apr 14 '11 at 07:47
  • Thanks Teoman. Now it works as intended. Looks kind of complicated right now though. At least for me as a beginner. – nabulke Apr 14 '11 at 07:51
  • Yes updating the UI thread (main thread mostly) from a background tread is a bit complicating at first but is quite logical once you get the hand of threading.. Been there done that:) – Teoman Soygul Apr 14 '11 at 07:53