显示一个模式用户界面的后台操作中间并继续用户界面、后台、模式、继续

2023-09-02 02:00:53 作者:聽雨﹏

我运行一个后台任务,它使用异步/计谋 WPF应用程序。任务是更新应用程序的状态的用户界面,因为它的进展。在这个过程中,如果某个条件已经满足,我需要出示模式窗口,使用户认识到这样的事件,然后继续进行处理,目前也更新了模态窗口的状态的用户界面。

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

问题modalUI.ShowDialog()是,它是一个阻塞调用,所以处理停止,直到对话框关闭。这不会是一个问题,如果该窗口是无模式,但它必须是模态的,如由项目要求。

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?

推荐答案

这可以通过执行 modalUI.ShowDialog()异步(在用户界面的未来迭代实现线程的消息循环)。 ShowDialogAsync 的下面的实现确实,通过使用 TaskCompletionSource ( EAP任务模式)和 SynchronizationContext.Post

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.

这样的执行工作流可能会有点棘手的理解,因为你的异步任务就是这会儿$ P $在两家独立的WPF留言板循环:主线程的一个和新的嵌套一(由启动ShowDialog的)。国际海事组织,这是完全正常的,我们只是采取的异步/计谋状态机,由C#编译器所提供的的优势。

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.

虽然,当你的任务告一段落,而模态窗口仍处于打开状态,你可能要等待用户将其关闭。这就是 CloseDialogAsync 做以下。此外,当用户关闭在任务执行过程中的对话框,你或许应该考虑的情况下(AFAIK,一个WPF窗口不能重复使用多个的ShowDialog 电话)。

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).

下面code对我的作品:

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

下面是一个稍微不同的方法,它使用 Task.Factory.StartNew 来调用 modalUI.ShowDialog ()异步的。返回工作以后可以期待,以确保用户关闭模式对话框。

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