简体   繁体   中英

How to notify the running thread that application is going to shut down in .net?

I have a requirement that, I need to run a method in the secondary thread(long running process), when the application is closing normally/abnormally I need to store the information of the secondary thread's method how much it is processed.

So when the next application starts I need to start the secondary thread's method from the point it is stopped.

Questions:

  1. How can we achieve it?
  2. How to intimate the thread that the application is going to shut down?

I guess that the best way would be to periodically save the progress of your secondary thread (to disk...) and resume from the last saved point when application (and your thread) is restarted.

Every other way seems like woodoo to me and will be hard to implement and debug.

In the secondary thread you could technically tie into the AppDomain.ProcessExit and AppDomain.UnhandledException events.

A word of caution though, both of those events are last chance type events and have some caveats to them. A thorough reading of the MSDN docs on each event before using them is warranted.

It sounds like you problem is a candidate for using a BackgroundWorker . It provides for progress and cancellation notification. Please see BackgroundWorker docs for an example.

When you initiate or detect that the application is going to shutdown, you can call CancelAsync on the background worker instance. Inside the handler for the BackgroundWorker.DoWork event, you can examine the event args periodically to see if cancellation is requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM