Syed
Syed

Reputation: 931

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?

Upvotes: 2

Views: 440

Answers (3)

Josh
Josh

Reputation: 44906

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.

Upvotes: 1

Monroe Thomas
Monroe Thomas

Reputation: 5042

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.

Upvotes: 1

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

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.

Upvotes: 2

Related Questions