Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c# - Show a modal UI in the middle of background operation and continue

I have a WPF application running a background task which uses async/await. The task is updating the app's status UI as it progresses. During the process, if a certain condition has been met, I am required to show a modal window to make the user aware of such event, and then continue processing, now also updating the status UI of that modal window.

This is a sketch version of what I am trying to achieve:

async Task AsyncWork(int n, CancellationToken token)
{
    // prepare the modal UI window
    var modalUI = new Window();
    modalUI.Width = 300; modalUI.Height = 200;
    modalUI.Content = new TextBox();

    using (var client = new HttpClient())
    {
        // main loop
        for (var i = 0; i < n; i++)
        {
            token.ThrowIfCancellationRequested();

            // do the next step of async process
            var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);

            // update the main window status
            var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
            ((TextBox)this.Content).AppendText(info); 

            // show the modal UI if the data size is more than 42000 bytes (for example)
            if (data.Length < 42000)
            {
                if (!modalUI.IsVisible)
                {
                    // show the modal UI window 
                    modalUI.ShowDialog();
                    // I want to continue while the modal UI is still visible
                }
            }

            // update modal window status, if visible
            if (modalUI.IsVisible)
                ((TextBox)modalUI.Content).AppendText(info);
        }
    }
}

The problem with modalUI.ShowDialog() is that it is a blocking call, so the processing stops until the dialog is closed. It would not be a problem if the window was modeless, but it has to be modal, as dictated by the project requirements.

Is there a way to get around this with async/await?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be achieved by executing modalUI.ShowDialog() asynchronously (upon a future iteration of the UI thread's message loop). The following implementation of ShowDialogAsync does that by using TaskCompletionSource (EAP task pattern) and SynchronizationContext.Post.

Such execution workflow might be a bit tricky to understand, because your asynchronous task is now spread across two separate WPF message loops: the main thread's one and the new nested one (started by ShowDialog). IMO, that's perfectly fine, we're just taking advantage of the async/await state machine provided by C# compiler.

Although, when your task comes to the end while the modal window is still open, you probably want to wait for user to close it. That's what CloseDialogAsync does below. Also, you probably should account for the case when user closes the dialog in the middle of the task (AFAIK, a WPF window can't be reused for multiple ShowDialog calls).

The following code works for me:

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfAsyncApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Content = new TextBox();
            this.Loaded += MainWindow_Loaded;
        }

        // AsyncWork
        async Task AsyncWork(int n, CancellationToken token)
        {
            // prepare the modal UI window
            var modalUI = new Window();
            modalUI.Width = 300; modalUI.Height = 200;
            modalUI.Content = new TextBox();

            try
            {
                using (var client = new HttpClient())
                {
                    // main loop
                    for (var i = 0; i < n; i++)
                    {
                        token.ThrowIfCancellationRequested();

                        // do the next step of async process
                        var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);

                        // update the main window status
                        var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
                        ((TextBox)this.Content).AppendText(info);

                        // show the modal UI if the data size is more than 42000 bytes (for example)
                        if (data.Length < 42000)
                        {
                            if (!modalUI.IsVisible)
                            {
                                // show the modal UI window asynchronously
                                await ShowDialogAsync(modalUI, token);
                                // continue while the modal UI is still visible
                            }
                        }

                        // update modal window status, if visible
                        if (modalUI.IsVisible)
                            ((TextBox)modalUI.Content).AppendText(info);
                    }
                }

                // wait for the user to close the dialog (if open)
                if (modalUI.IsVisible)
                    await CloseDialogAsync(modalUI, token);
            }
            finally
            {
                // always close the window
                modalUI.Close();
            }
        }

        // show a modal dialog asynchronously
        static async Task ShowDialogAsync(Window window, CancellationToken token)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                RoutedEventHandler loadedHandler = (s, e) =>
                    tcs.TrySetResult(true);

                window.Loaded += loadedHandler;
                try
                {
                    // show the dialog asynchronously 
                    // (presumably on the next iteration of the message loop)
                    SynchronizationContext.Current.Post((_) => 
                        window.ShowDialog(), null);
                    await tcs.Task;
                    Debug.Print("after await tcs.Task");
                }
                finally
                {
                    window.Loaded -= loadedHandler;
                }
            }
        }

        // async wait for a dialog to get closed
        static async Task CloseDialogAsync(Window window, CancellationToken token)
        {
            var tcs = new TaskCompletionSource<bool>();
            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                EventHandler closedHandler = (s, e) =>
                    tcs.TrySetResult(true);

                window.Closed += closedHandler;
                try
                {
                    await tcs.Task;
                }
                finally
                {
                    window.Closed -= closedHandler;
                }
            }
        }

        // main window load event handler
        async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var cts = new CancellationTokenSource(30000);
            try
            {
                // test AsyncWork
                await AsyncWork(10, cts.Token);
                MessageBox.Show("Success!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

[EDITED] Below is a slightly different approach which uses Task.Factory.StartNew to invoke modalUI.ShowDialog() asynchronously. The returned Task can be awaited later to make sure the user has closed the modal dialog.

async Task AsyncWork(int n, CancellationToken token)
{
    // prepare the modal UI window
    var modalUI = new Window();
    modalUI.Width = 300; modalUI.Height = 200;
    modalUI.Content = new TextBox();

    Task modalUITask = null;

    try
    {
        using (var client = new HttpClient())
        {
            // main loop
            for (var i = 0; i < n; i++)
            {
                token.ThrowIfCancellationRequested();

                // do the next step of async process
                var data = await client.GetStringAsync("http://www.bing.com/search?q=item" + i);

                // update the main window status
                var info = "#" + i + ", size: " + data.Length + Environment.NewLine;
                ((TextBox)this.Content).AppendText(info);

                // show the modal UI if the data size is more than 42000 bytes (for example)
                if (data.Length < 42000)
                {
                    if (modalUITask == null)
                    {
                        // invoke modalUI.ShowDialog() asynchronously
                        modalUITask = Task.Factory.StartNew(
                            () => modalUI.ShowDialog(),
                            token,
                            TaskCreationOptions.None,
                            TaskScheduler.FromCurrentSynchronizationContext());

                        // continue after modalUI.Loaded event 
                        var modalUIReadyTcs = new TaskCompletionSource<bool>();
                        using (token.Register(() => 
                            modalUIReadyTcs.TrySetCanceled(), useSynchronizationContext: true))
                        {
                            modalUI.Loaded += (s, e) =>
                                modalUIReadyTcs.TrySetResult(true);
                            await modalUIReadyTcs.Task;
                        }
                    }
                }

                // update modal window status, if visible
                if (modalUI.IsVisible)
                    ((TextBox)modalUI.Content).AppendText(info);
            }
        }

        // wait for the user to close the dialog (if open)
        if (modalUITask != null)
            await modalUITask;
    }
    finally
    {
        // always close the window
        modalUI.Close();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...