C# - 终止Application.Run()

Jon*_*s W 6 .net c# multithreading winforms

有没有办法干净地终止System.Windows.Forms.Application.Run()从另一个线程调用发出的消息循环?

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

提前致谢!

Han*_*ant 12

使用ApplicationContext类来保持对线程的引用.像这样:

    ApplicationContext threadContext;

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

    private void stopLoop() {
        threadContext.ExitThread();
        threadContext = null;
    }
Run Code Online (Sandbox Code Playgroud)