Jonas W
Jonas W

Reputation: 373

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!

Upvotes: 6

Views: 1308

Answers (1)

Hans Passant
Hans Passant

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

Related Questions