How to detect when main thread terminates?

前端 未结 5 1235
难免孤独
难免孤独 2020-12-21 10:26

What I need to know:

I would like to detect when a the main thread (process?) terminates so that I can ensure certain actions are performed before i

5条回答
  •  旧时难觅i
    2020-12-21 11:19

    I don't know how old this thread is, but I've had a similar problem whcih was a little tough for me to solve.

    I had a WinForms application that was not firing any of the above forementioned events when a user logged out. Wraaping the Application.Run() in a try finally didn't work either.

    Now to get around this you would have to using PInvoke into Win32 API's to achieve this. Well you did prior to .NET 2.0 anyways. Luckly MS introduced a new class called SystemEvents. With this class you can catch a SessionEnd event. This event allows you to cleanup when the OS want to terminate your app. There is no .NET time limit o this event it appears, although the OS will eventually kill your app if you take too long. This is a little more than 3 seconds, although 3 seconds should be plenty of time to cleanup.

    Secondly my other problem was I wanted my worker thread to terminate the main thread once it was finished its work. With an Application.Run() this was hard to achieve. What I ended up doing was calling Application.Run() with a shared Application context. The thread is then able to call ApplicationContext.ThreadExit() to force the Application.Run to return. This seems to work quite nicely.

    Hope this helps someone.

    Regards

    NozFX

提交回复
热议问题