有没有办法干净地终止从另一个线程调用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()?
提前致谢!
答案 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;
}