I created an application that should periodically perform some tasks using threads. I am not sure if this is the best way to do this, so I would really appreciate it if anyone could suggest a better way.
So I did it:
This is a class that includes the functions of a continuous process (searching for inactive sessions and clearing idle items):
public class SessionCleaner
{
private SQLWorks sqlWorks;
public SessionCleaner()
{
sqlWorks = new SQLWorks();
}
private void cleanIdleSessions()
{
sqlWorks.CleanIdleSessions(10);
}
public void DoCleanIdleSessions()
{
while(true)
{
cleanIdleSessions();
Thread.Sleep(5000);
}
}
}
This is the main form in which the stream 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!
source
share