c# - 在后台操作中间显示模态 UI 并继续

标签 c# .net wpf asynchronous async-await

我有一个运行后台任务的 WPF 应用程序,它使用 async/await。该任务正在更新应用程序的状态 UI。在此过程中,如果满足某个条件,我需要显示一个模态窗口让用户知道该事件,然后继续处理,现在还更新该模态窗口的状态 UI。

这是我想要实现的目标的草图版本:

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);
        }
    }
}

modalUI.ShowDialog() 的问题在于它是一个阻塞调用,因此处理会停止,直到对话框关闭。如果窗口是无模式的,那将不是问题,但它必须是模式的,如项目要求所规定的那样。

有没有办法用 async/await 来解决这个问题?

最佳答案

这可以通过异步执行 modalUI.ShowDialog() 来实现(在 UI 线程的消息循环的 future 迭代中)。 ShowDialogAsync 的以下实现通过使用 TaskCompletionSource ( EAP task pattern ) 和 SynchronizationContext.Post 来实现。

这样的执行工作流可能有点难以理解,因为您的异步任务现在分布在两个独立的 WPF 消息循环中:主线程的循环和新的嵌套循环(由 ShowDialog 启动)。 IMO,这很好,我们只是利用 C# 编译器提供的 async/await 状态机。

尽管如此,当您的任务结束而模态窗口仍处于打开状态时,您可能希望等待用户将其关闭。这就是 CloseDialogAsync 下面所做的。此外,您可能应该考虑用户在任务中间关闭对话框的情况(AFAIK,WPF 窗口不能重复用于多个 ShowDialog 调用)。

以下代码适用于我:

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());
            }
        }
    }
}

[已编辑] 下面是一种略有不同的方法,它使用 Task.Factory.StartNew 异步调用 modalUI.ShowDialog()。稍后可以等待返回的 Task 以确保用户已关闭模式对话框。

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();
    }
}

关于c# - 在后台操作中间显示模态 UI 并继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20917996/

相关文章:

c# - 使用回调从WCF发送混合声音

c# - 如何用C#绘制表格?

wpf - TabControl - 使 TabItem 出现在内容顶部

c# - UserControl 中的 DependencyProperty bool

c# - 如何从 ASP.NET 调用具有多个输入值的 MySQL 存储过程

c# - 如何通过 Unity 容器配置 HttpClient?

c# - 以前工作的 REGEX 匹配现在失败

c# - 查找哪个模块阻塞了 UI 线程

wpf - 类成员定义为静态或非静态时的行为不同

c# - 我的 ItemsControl 和数据绑定(bind)有什么问题?