2

I am trying to implement a system for closing all modal and non-modal windows in a WPF application (with the exception of the main application window.) When these windows are closed, any code awaiting the result of a dialog should be abandoned.

So far, I've considered/attempted two strategies:

  1. Close and restart the application.
  2. Close all the windows and rely on task cancellation exceptions to abandon all code that was waiting for dialog results. (It bubbles up to the App level and then becomes handled.)

The first solution definitely gets the application to close and will suffice for automatic logout, but I am extremely uncomfortable with code that continues to execute after the dialog it was waiting for has been closed. Is there a nice way to stop the execution of that code?

The second solution has been working relatively well (calling code is aborted) but has one critical flaw: on occasion, some combination of modal and non-modal windows closing in quick succession will cause the application to lock up on a ShowDialog call. (At least, when you pause execution, that's where it ends up.) This is strange because breakpoints clearly demonstrate that the Closed event is being raised on all windows that I intend to close. The result that the end user sees is a login screen that cannot be clicked on but can be tabbed into. So strange! Attempts to dispatch the call at different priorities have been unsuccessful, but a Task.Delay for 100ms might have done the trick. (That's not a real solution, though.)

If each open popup is awaiting a TaskCompletionSource in the background, and, upon completion of the TCS, tries to use the dispatcher to invoke Close on itself, why would one (or more) of the dialogs still be blocking on ShowDialog, even after seeing the Closed event be raised? Is there a way to properly dispatch these calls to Close so they complete successfully? Do I need to be particular about the order in which the windows close?

Some pseudocode-C#-hybrid examples:

class PopupService
{
    async Task<bool> ShowModalAsync(...)
    {
        create TaskCompletionSource, publish event with TCS in payload
        await and return the TCS result
    }

    void ShowModal(...)
    {
        // method exists for historical purposes. code calling this should
        // probably be made async-aware rather than relying on the blocking
        // behavior of Window.ShowDialog
        create TaskCompletionSource, publish event with TCS in payload
        rethrow exceptions that are set on the Task after completion but do not await
    }

    void CloseAllWindows(...)
    {
        for every known TaskCompletionSource driving a popup interaction
            tcs.TrySetCanceled()
    }
}

class MainWindow : Window
{
    void ShowModalEventHandler(...)
    {
        create a new PopupWindow and set the owner, content, etc.
        var window = new PopupWindow(...) { ... };
        ...
        window.ShowDialog();
    }
}

class PopupWindow : Window
{
    void LoadedEventHandler(...)
    {
        ...
        Task.Run(async () =>
        {
            try
                await the task completion source
            finally
                Dispatcher.Invoke(Close, DispatcherPriority.Send);
        });

        register closing event handlers
        ...
    }

    void ClosedEventHandler(...)
    {
        if(we should do something with the TCS)
            try set the TCS result so the popup service caller can continue
    }
}

3 Answers 3

2

With Window.ShowDialog you create a nested Dispather message loop. With await, it's possible to "jump" on that inner loop and continue the logical execution of an async method there, e.g.:

var dialogTask = window.ShowDialogAsync();
// on the main message loop
await Task.Delay(1000);
// on the nested message loop
// ...
await dialogTask;
// expecting to be back on the main message loop

Now, if dialogTask gets completed via TaskCompletionSource before the corresponding Window.ShowDialog() call returns to the caller, the above code may still end up on the nested message loop, rather than on the main core message loop. E.g., this may happen if TaskCompletionSource.SetResult/TrySetCanceled is called inside the dialog's Window.Closed event handler, or right before/after Window.Close() call. This may create undesired reentrancy side effects, including deadlocks, too.

By looking at your pseudocode, it's hard to tell where the deadlock may be. What is worrying is that you're using Task.Run only to await a task that completes on the main UI thread, or to invoke a synchronous callback on the main UI thread from a pool thread (via Dispatcher.Invoke). You certainly shouldn't need Task.Run here.

I use the following version of ShowDialogAsync for a similar purpose. It makes sure any inner message loops started by nested ShowDialogAsync calls exit before this particular ShowDialogAsync task is complete:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        // testing ShowDialogAsync
        async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var modal1 = new Window { Title = "Modal 1" };
            modal1.Loaded += async delegate
            {
                await Task.Delay(1000);

                var modal2 = new Window { Title = "Modal 2" };
                try
                {
                    await modal2.ShowDialogAsync();
                }
                catch (OperationCanceledException)
                {
                    Debug.WriteLine("Cancelled: " + modal2.Title);
                }
            };

            await Task.Delay(1000);
            // close modal1 in 5s
            // this would automatically close modal2
            var cts = new CancellationTokenSource(5000); 
            try
            {
                await modal1.ShowDialogAsync(cts.Token);
            }
            catch (OperationCanceledException)
            {
                Debug.WriteLine("Cancelled: " + modal1.Title);
            }
        }
    }

    /// <summary>
    /// WindowExt
    /// </summary>
    public static class WindowExt
    {
        [ThreadStatic]
        static CancellationToken s_currentToken = default(CancellationToken);

        public static async Task<bool?> ShowDialogAsync(
            this Window @this, 
            CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();
            var previousToken = s_currentToken;
            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(previousToken, token))
            {
                var currentToken = s_currentToken = cts.Token;
                try
                {
                    return await @this.Dispatcher.InvokeAsync(() =>
                    {
                        using (currentToken.Register(() => 
                            @this.Close(), 
                            useSynchronizationContext: true))
                        {
                            try
                            {
                                var result = @this.ShowDialog();
                                currentToken.ThrowIfCancellationRequested();
                                return result;
                            }
                            finally
                            {
                                @this.Close();
                            }
                        }
                    }, DispatcherPriority.Normal, currentToken);
                }
                finally
                {
                    s_currentToken = previousToken;
                }
            }
        }
    }
}

This allows you to cancel the most outer modal window via the associated CancelationToken, and that would automatically close any nested modal windows (those opened with ShowDialogAsync) and exit their corresponding message loops. So, your logical execution flow would end up on the correct outer message loop.

Note it still doesn't guarantee the correct logical order of closing multiple modal windows, if that matters. But it guarantees that the tasks returned by multiple nested ShowDialogAsync calls will get completed in the correct order.

4
  • Do you think there's any way to have this work properly without having the ShowDialogAsync method be async? I'd assume I cannot just call Task.Wait() as I'll probably end up deadlocking somewhere, but I'm really not looking forward to updating all of our code to support async/await. There's an overload that exists right now which relies on the blocking behavior provided by ShowDialog.
    – Guttsy
    Commented Jul 27, 2015 at 15:11
  • @Guttsy, isn't ShowModalAsync asynchronous too in your version (i.e., returning a Task<bool?>)?
    – noseratio
    Commented Jul 27, 2015 at 21:41
  • We had a separate service that was used for dialogs that I shimmed into the design posted here. I neglected to document this here. The problem is that original service was never intended to work asynchronously. If that's unavoidable, so be it. It can be fixed, but leaving the call as blocking would be great for the moment.
    – Guttsy
    Commented Jul 28, 2015 at 13:11
  • @Guttsy, not sure I understand your workflow, but if you want to break out of uncontrolled Window.ShowDialog loops, you can queue an exception via BeginInvoke, to be thrown on the innermost loop. E.g., Dispatcher.BeginInvoke(new Action(() => { throw new OperationCanceledException(token))). If uncaught, it should bubble up and out of all modal loops, effectively terminating them. You'd need to handle it somewhere though, perhaps inside a custom Application.Run.
    – noseratio
    Commented Jul 29, 2015 at 1:58
2

I am not sure that this is gonna fix your issue, but in my case, I created extension methods to help mixing async code and window lifetime management. For example, you can create a ShowDialogAsync() that returns task that will complete when the window is actually closed. A CancellationToken can also be provided to close the dialog automatically if you request a cancellation.

public static class WindowExtension
{
    public static Task<bool?> ShowDialogAsync(this Window window, CancellationToken cancellationToken = new CancellationToken())
    {
        var completionSource = new TaskCompletionSource<bool?>();

        window.Dispatcher.BeginInvoke(new Action(() =>
        {
            var result = window.ShowDialog();
            // When dialog is closed, set the result to complete the returned task. If the task is already cancelled, it will be discarded.
            completionSource.TrySetResult(result);
        }));

        if (cancellationToken.CanBeCanceled)
        {
            // Gets notified when cancellation is requested so that we can close window and cancel the returned task 
            cancellationToken.Register(() => window.Dispatcher.BeginInvoke(new Action(() =>
            {
                completionSource.TrySetCanceled();
                window.Close();
            })));
        }

        return completionSource.Task;
    }
}

In your UI code, you would use the ShowDialogAsync() method like the following. As you can see, when the task is cancelled, the dialog is closed and an OperationCanceledException exception is thrown stopping the flow of your code.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    try
    {
        YourDialog dialog = new YourDialog();
        CancellationTokenSource source = new CancellationTokenSource(TimeSpan.FromSeconds(3));
        await dialog.ShowDialogAsync(source.Token);
    }
    catch (OperationCanceledException ex)
    {
        MessageBox.Show("Operation was cancelled");
    }
}
6
  • Doing a BeginInvoke might very well solve the problem. I haven't been able to reproduce the issue in the few times I've tried after making that change, but I know BeginInvoke gave me some grief the last time I tried it. I know I'm going to have to do a bunch of refactoring since there's a fair amount of code that's relying on ShowDialog blocking execution. I'll keep testing it.
    – Guttsy
    Commented Jul 24, 2015 at 18:26
  • Unfortunately, it still seems to get stuck on ShowDialog inside the BeginInvoke, but I like the idea.
    – Guttsy
    Commented Jul 24, 2015 at 18:46
  • I tested the sample in my example and if I put a breakpoint after the ShowDialog() inside the BeginInvoke() and I press the button in my app, the breakpoint gets hit after 3 seconds (cancellation source timeout). Could you please provide the code that blocks when you use my example?
    – Absolom
    Commented Jul 24, 2015 at 19:45
  • 1
    @Absolom, I've up-voted this but I have two concerns: 1) it doesn't terminate any nested ShowDialogAsync calls; 2) After await dialog.ShowDialogAsync() it still may end up on the nested message loop, because of the way you signal the completion of completionSource. See my answer for some more details.
    – noseratio
    Commented Jul 27, 2015 at 1:23
  • 1
    @Noseratio, I wasn't aware of the potential problems of my solution but your comments make perfect sense. Your solution should be the upvoted one. Feel free to downvote your upvote on my answer!
    – Absolom
    Commented Jul 27, 2015 at 14:12
0

This is JUST for the first part of your issue (closing the windows).

if you do not need any of the results of the windows here is some simple code just to close all but the main window.

This is executing from my main window but you can change the if statement to look for your mainwindow instead if running from alternate area.

foreach(Window item in App.Current.Windows)
            {
                if(item!=this)
                    item.Close();
            }

As for other threads I am unsure although as mentioned above if you have a list of handles to the threads then you should be able to traverse that as well and kill them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.