Do not run the thread already running in windows service

Hello everyone,

Nowadays I have been developing a windows service that needs to be triggered per hour. The job my service does may last in less than 1 hour or may last in more than 1 hour. So what I needed to develop is to not let the windows service trigger if there is already a running job.

Researching that I found this page on stackoverflow. I tried what Matt Johnson replied to the question and it worked perfectly for me and I wanted to share it. With his reply I learned a new keyword in C# : volatile

private volatile bool _executing;

private void TimerElapsed(object state)
{
    if (_executing)
        return;

    _executing = true;

    try
    {
        // do the real work here
    }
    catch (Exception e)
    {
        // handle your error
    }
    finally
    {
        _executing = false;
    }
}

Hope that helps!

Leave a Reply

Your email address will not be published. Required fields are marked *