Guarantee code execution even on process kill

前端 未结 4 632
太阳男子
太阳男子 2020-12-10 10:39

I need to execute a portion of code (the state save) on the process stopping - by itself, by user, by task manager, etc.

Is it possible?

try {} finally

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 11:30

    I was looking around for a somewhat different reason than what is posted, but I came up with a pretty good solution for myself and it might useful to state here:

    NOTE: To those that know what it is, this is essentially the 'Heartbeat' design pattern.

    1) In addition to the code running that will 'die' (ie be killed), add code to this project such that it spawns a thread (or possibly another method?) upon initialization, and all the thread does is run a never-ending while loop (but make sure it sleeps at least a few seconds or even 1 minute between iterations) and in the while loop, record an indicator to indicate your app is 'alive' (ie the 'heartbeat'). I personally recommend setting a value in either the DB, or perhaps a file, that is the current timestamp (ie DateTime.Now)

    2) Now that you are recording the 'heartbeat', create another app (ie another process) that does nothing but reads the heartbeat value (ie the current timestamp) and does this in a never-ending while loop. Once its determined that the heartbeat value is 'bad' (ie maybe if, say, HeartBeatTimestamp + 5 min < DateTime.Now), you can now run your code that you desire to run 'once the process is killed'

    Hope this helps :) Feel free to research the 'Heartbeat' design pattern from other resources to if you want to know more!

    Cheers,

    Jeff

提交回复
热议问题