I have a small background thread that works for application life - however, when the application shuts down, the thread should exit gracefully.
The problem is that the thread executes some code at intervals of 15 minutes, which means that it sleeps ALOT.
Now, to get rid of it, I throw an interrupt on it - however, my question is if there is a better approach to this, since interrupts throw a ThreadInterruptedException.
Here is the gist of my code (somewhat pseudo):
public class BackgroundUpdater : IDisposable
{
private Thread myThread;
private const int intervalTime = 900000;
public void Dispose()
{
myThread.Interrupt();
}
public void Start()
{
myThread = new Thread(ThreadedWork);
myThread.IsBackground = true;
myThread.Priority = ThreadPriority.BelowNormal;
myThread.Start();
}
private void ThreadedWork()
{
try
{
while (true)
{
Thread.Sleep(900000);
DoWork();
}
}
catch (ThreadInterruptedException)
{
}
}
}
source
share