In my c# windows service i’m starting several threads. Each thread should dispose it’s objects after a specific period of time with no activity.
I tried the System.Threading.Timer and System.Timers.Timer classes but they all raise the events on a different thread.
This is what’s happining:
- create several threads during service.start
- each thread monitors a directory and activates a resource extensive function for every new file
- After a 1 hour of no activity inside the thread (no files are handled during that period) i want to cleanup the resources inside that thread (structuremap, threadlocal classes)
Assuming that by “a period of no activity” you mean a thread that has been in the WaitSleepJoin for too long, you can interrupt such a thread by calling its Interrupt Method:
This will cause a ThreadInterruptedException to be thrown in the target thread. Hence, you can catch the exception in order to dispose the thread’s resources:
Now you need some way of tracking the amount of time each thread stays inactive. For instance, create a method that all threads must call before going to sleep or waiting on a mutex:
Finally, to check for how long a specific thread has been inactive, call the following method:
I believe that using this pattern you will be able to create a thread manager class that meets your requirements.