C# - 终止Application.Run()

时间:2011-09-10 16:14:15

标签: c# .net winforms multithreading

有没有办法干净地终止从另一个线程调用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()?

提前致谢!

1 个答案:

答案 0 :(得分: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;
    }