在UI线程上调用异步方法 [英] Call async method on UI thread

查看:81
本文介绍了在UI线程上调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 IdentityServer 身份验证创建WPF客户端.我正在使用他们的OidcClient进行登录.当我的应用程序同步时,它完全是异步的,如果不付出巨大的努力就无法进行重构.打电话

var result = await _oidcClient.LoginAsync();

不等待结果.调用Wait().Result会导致死锁.将其包装到其他Task.Run时,抱怨该方法未在UI线程上运行(它将打开带有登录对话框的浏览器).

您有什么想法,如何解决?我是否需要编写自定义同步OidcClient?

解决方案

与其他类似的情况一样,您需要在不进行大量重构的情况下将旧版应用引入异步,我建议您使用简单的请稍候..."模态对话框.该对话框将启动一个异步操作,并在该操作完成后自行关闭.

Window.ShowDialog 是一种同步API,它会阻塞主UI,并且仅在模式对话框关闭时才返回到调用方.但是,它仍然运行嵌套的消息循环并泵送消息.因此,与使用容易发生死锁的Task.Wait()相反,异步任务继续回调仍会被执行.

这是一个基本但完整的WPF示例,使用Task.Delay()模拟_oidcClient.LoginAsync()并在UI线程上执行它,有关详细信息,请参考WpfTaskExt.Execute.

取消支持是可选的;如果无法取消实际的LoginAsync,则可以防止该对话框过早关闭.

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

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            var button = new Button() { Content = "Login", Width = 100, Height = 20 };
            button.Click += HandleLogin;
            this.Content = button;
        }

        // simulate _oidcClient.LoginAsync
        static async Task<bool> LoginAsync(CancellationToken token)
        {
            await Task.Delay(5000, token);
            return true;
        }

        void HandleLogin(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = WpfTaskExt.Execute(
                    taskFunc: token => LoginAsync(token),
                    createDialog: () =>
                        new Window
                        {
                            Owner = this,
                            Width = 320,
                            Height = 200,
                            WindowStartupLocation = WindowStartupLocation.CenterOwner,
                            Content = new TextBox
                            {
                                Text = "Loggin in, please wait... ",
                                HorizontalContentAlignment = HorizontalAlignment.Center,
                                VerticalContentAlignment = VerticalAlignment.Center
                            },
                            WindowStyle = WindowStyle.ToolWindow
                        },
                    token: CancellationToken.None);

                MessageBox.Show($"Success: {result}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    public static class WpfTaskExt
    {
        /// <summary>
        /// Execute an async func synchronously on a UI thread,
        /// on a modal dialog's nested message loop
        /// </summary>
        public static TResult Execute<TResult>(
            Func<CancellationToken, Task<TResult>> taskFunc,
            Func<Window> createDialog,
            CancellationToken token = default(CancellationToken))
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(token);

            var dialog = createDialog();
            var canClose = false;
            Task<TResult> task = null;

            async Task<TResult> taskRunner()
            {
                try
                {
                    return await taskFunc(cts.Token);
                }
                finally
                {
                    canClose = true;
                    if (dialog.IsLoaded)
                    {
                        dialog.Close();
                    }
                }
            }

            dialog.Closing += (_, args) =>
            {
                if (!canClose)
                {
                    args.Cancel = true; // must stay open for now
                    cts.Cancel();
                }
            };

            dialog.Loaded += (_, __) =>
            {
                task = taskRunner();
            };

            dialog.ShowDialog();

            return task.GetAwaiter().GetResult();
        }
    }
}

I'm trying to create WPF client with IdentityServer authentication. I'm using their OidcClient to get logged in. It's whole async while my app is sync and can't be refactored without huge effort. Calling

var result = await _oidcClient.LoginAsync();

doesn't wait for the result. Calling Wait() or .Result causes deadlock. Wrapping it to other Task.Run is complaining that the method is not running on UI thread (it opens browser with login dialog).

Do you have any idea, how to solve this? Do I need to write custom sync OidcClient?

解决方案

As with other similar cases where you need to introduce asynchrony to a legacy app without much refactoring, I'd recommend using a simple "Please wait..." modal dialog. The dialog initiates an async operation and closes itself when the operation has finished.

Window.ShowDialog is a synchronous API in the way it blocks the main UI and only returns to the caller when the modal dialog has been closed. However, it still runs a nested message loop and pumps messages. Thus, the asynchronous task continuation callbacks still get pumped and executed, as opposed to using a deadlock-prone Task.Wait().

Here is a basic but complete WPF example, mocking up _oidcClient.LoginAsync() with Task.Delay() and executing it on the UI thread, refer to WpfTaskExt.Execute for the details.

Cancellation support is optional; if the actual LoginAsync can't be cancelled, the dialog is prevented from being closed prematurely.

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

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            var button = new Button() { Content = "Login", Width = 100, Height = 20 };
            button.Click += HandleLogin;
            this.Content = button;
        }

        // simulate _oidcClient.LoginAsync
        static async Task<bool> LoginAsync(CancellationToken token)
        {
            await Task.Delay(5000, token);
            return true;
        }

        void HandleLogin(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = WpfTaskExt.Execute(
                    taskFunc: token => LoginAsync(token),
                    createDialog: () =>
                        new Window
                        {
                            Owner = this,
                            Width = 320,
                            Height = 200,
                            WindowStartupLocation = WindowStartupLocation.CenterOwner,
                            Content = new TextBox
                            {
                                Text = "Loggin in, please wait... ",
                                HorizontalContentAlignment = HorizontalAlignment.Center,
                                VerticalContentAlignment = VerticalAlignment.Center
                            },
                            WindowStyle = WindowStyle.ToolWindow
                        },
                    token: CancellationToken.None);

                MessageBox.Show($"Success: {result}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    public static class WpfTaskExt
    {
        /// <summary>
        /// Execute an async func synchronously on a UI thread,
        /// on a modal dialog's nested message loop
        /// </summary>
        public static TResult Execute<TResult>(
            Func<CancellationToken, Task<TResult>> taskFunc,
            Func<Window> createDialog,
            CancellationToken token = default(CancellationToken))
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(token);

            var dialog = createDialog();
            var canClose = false;
            Task<TResult> task = null;

            async Task<TResult> taskRunner()
            {
                try
                {
                    return await taskFunc(cts.Token);
                }
                finally
                {
                    canClose = true;
                    if (dialog.IsLoaded)
                    {
                        dialog.Close();
                    }
                }
            }

            dialog.Closing += (_, args) =>
            {
                if (!canClose)
                {
                    args.Cancel = true; // must stay open for now
                    cts.Cancel();
                }
            };

            dialog.Loaded += (_, __) =>
            {
                task = taskRunner();
            };

            dialog.ShowDialog();

            return task.GetAwaiter().GetResult();
        }
    }
}

这篇关于在UI线程上调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆