简体   繁体   中英

C# - Terminating Application.Run()

Is there a way to cleanly terminate a message loop issued by calling System.Windows.Forms.Application.Run() from another thread?

Thread messageLoop = new Thread(() => Application.Run());
messageLoop.SetApartmentState(ApartmentState.STA);
messageLoop.Start();
//How to terminate thread like on Application.ExitThread() without calling Thread.Abort()?

Thanks in advance!

Use the ApplicationContext class to keep a reference to the thread. Like this:

    ApplicationContext threadContext;

    private void startLoop() {
        threadContext = new ApplicationContext();
        var messageLoop = new Thread(() => Application.Run(threadContext));
        messageLoop.Start();
    }

    private void stopLoop() {
        threadContext.ExitThread();
        threadContext = null;
    }

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