简体   繁体   中英

What is the correct way to close a second Application loop?

    public static void Main()
    {
        Form formOnThisMessageLoop = new Form();
        formOnThisMessageLoop.Show();

        Form formOnOtherMessageLoop = new Form();

        Task.Factory.StartNew(
            () =>
            {                                        
                Application.Run(formOnOtherMessageLoop);                    
            }
         );
        //Thread.Sleep(50);
        formOnOtherMessageLoop.HandleCreated += (obj, args) =>
        formOnOtherMessageLoop.Invoke(new Action(() => { formOnOtherMessageLoop.Close(); })); //Value Close() cannot be called while doing CreateHandle().
        Application.Run();                         

        Console.Read();
    }

I'm experimenting with various ways to close a form on a second message loop. How can I synchronize my threads correctly in such a case? Also, do I need to call Application.Exit() twice or is Form.Close() the best I can do? I see Application.Run() keeping my dead thread alive. That's my concern with it. Assume the Main thread could live a long time.

Form.Close() will exit that other message loop as long as the Form is passed in as a parameter to Application.Run(formOnOtherMessageLoop) as you have done. If instead you wrote Application.Run() and called Form.Close() the application will not exit.

But why do you need another message loop? Especially the way that you are doing it, because that will consume a thread pool thread to run said other message loop.

That's almost always a bad idea- this coming from someone who has worked with very latency-sensitive applications that were implemented using multiple message loops (usually poorly, with lots of bugs).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM