I created an application which has to periodically perform some tasks using threads. I am not sure if this is the best way for doing it so I would really appreciate if anyone could suggest a better way.
This is the way I did it:
This is the class which includes the functions for a continuous process (looking for inactive sessions and cleaning idle items):
public class SessionCleaner
{
private SQLWorks sqlWorks;
public SessionCleaner()
{
sqlWorks = new SQLWorks();
}
private void cleanIdleSessions()
{
//this function deletes sessions from database
sqlWorks.CleanIdleSessions(10);
}
//this is an endless loop for executing the cleaning every 5 seconds
public void DoCleanIdleSessions()
{
while(true)
{
cleanIdleSessions();
Thread.Sleep(5000);
}
}
}
This is the main form where the thread is initialized:
public partial class FormMain : Form
{
...
public FormMain()
{
InitializeComponent();
...
startSessionCleaner();
...
}
private void startSessionCleaner()
{
initializeSessionCleanerThread();
sessionCleanerThread.Start();
}
private void initializeSessionCleanerThread()
{
sessionCleaner = new SessionCleaner();
sessionCleanerThread = new Thread(new ThreadStart(sessionCleaner.DoCleanIdleSessions));
}
private void terminateSessionCleanerThread()
{
try
{
sessionCleanerThread.Join(1000);
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
terminateSessionCleanerThread();
}
Thanks!