What is the best way to start a continuous process in your thread?

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()
    {
        //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 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!

+3
source share
2 answers

, , - - ? Join, , , , , while(true). (volatile) bool- - ( SessionCleaner), / while - :

volatile bool keepRunning = true;

( false Join ).

sessionCleanerThread ( ), , , .

+2

terminateSessionerThread() , -, . -, .

Thread() ThreadPool.QueueUserWorkItem(). , , QUWI. . Thread() . , , .

5 ? , , . WinForms . Windows, ..

0

Source: https://habr.com/ru/post/1705516/


All Articles