winforms 如何从非UI线程创建窗体

1tu0hz3e  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(127)

我使用类似的代码,但这是行不通的,因为客户端subscibe回调操作是在非UI线程运行。如何将回调操作计划到Windows窗体UI线程?

internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var context = new ProgramApplicationContext())
            {
                Application.Run(context);
            }
        }
    }

    internal class ProgramApplicationContext : ApplicationContext
    {
        public ProgramApplicationContext()
        {
            ...
            _client.subscribe("event", message => {
                var form = new CommunicationForm();
                form.Show();
            });
        }
    }
gopyfrb3

gopyfrb31#

您可以使用SynchronizationContext在UI线程上创建表单。

public ProgramApplicationContext()
{
    ...
    var ctx = SynchronizationContext.Current;
    _client.subscribe("event", message => {
        ctx.Send(state => {
            var form = new CommunicationForm();
            form.Show();
        }, null);
    });
}

相关问题