Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create windows forms Form from non UI thread

I use code similar to this, but this is not working, becouse client subscibe callback action is running in non UI thread. How can I schedule callback action to windows forms UI thread?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use SynchronizationContext to create the form on the UI thread.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading