Reputation: 373
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!
Upvotes: 6
Views: 1308
Reputation: 941257
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;
}
Upvotes: 12