How to detect when main thread terminates?

前端 未结 5 1234
难免孤独
难免孤独 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条回答
  •  时光取名叫无心
    2020-12-21 11:24

    What exactly do you want to find out?

    • When the process terminates? (Just because the AppDomain is unloaded doesn't necessarily mean that the entire process is terminating)
    • When the main thread terminates (If there are other non-background threads, the main thread can terminate without the process terminating (or AppDomain unloading)

    So they're not quite the same thing.

    Anyway, it is generally dangerous to have log messages buffered in memory at all. What happens if someone turns off the power? Or if I terminate your process through Task Manager? All your log messages are gone. So often, you'll want unbuffered writes in your log, to get messages pushed to disk immediately.

    Anyway, another (more robust) approach might be to run the logger itself in a non-background thread. That way, even if the rest of the application terminates, the logger won't, so the process is kept alive. Then you just have to set some flag when the rest of the app terminates, to let the logger know that it too should close once it has written out all pending log messages.

    It still won't save you from the case where the system loses power or someone forcibly termianates the process on the OS-level, but it will handle all cases where the application closes normally, and gives you unlimited time to perform clean-up actions (since the process isn't actually terminating yet, it's still got one live thread)

提交回复
热议问题