Timer in windows Service C# Finish before the task ended

عبدالمجيد العتيبي 21 Reputation points
2025-01-21T08:04:12.0133333+00:00

Hello,

I am creating a Windows service using C#. The program is designed to send SMS messages every 3 seconds. However, sometimes the task takes longer than 3 seconds, resulting in duplicate messages being sent to the user.

What advice do you have for addressing this issue?

and What happen if the Timer in windows Service Finish before the task ended

Windows
Windows
A family of Microsoft operating systems that run across personal computers, tablets, laptops, phones, internet of things devices, self-contained mixed reality headsets, large collaboration screens, and other devices.
5,728 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,217 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 48,776 Reputation points Microsoft Vendor
    2025-01-21T09:32:23.8766667+00:00

    Hi @عبدالمجيد العتيبي , Welcome to Microsoft Q&A,

    Ensure that only one instance of the SMS-sending task is running at a time. You can achieve this by:

    • Using a locking mechanism.
    • Checking a flag to prevent overlapping executions.
    
    private static bool isTaskRunning = false;
    
    private void TimerElapsed(object sender, ElapsedEventArgs e)
    
    {
    
        if (isTaskRunning) return;
    
        isTaskRunning = true;
    
        try
    
        {
    
            SendSmsMessages();
    
        }
    
        finally
    
        {
    
            isTaskRunning = false;
    
        }
    
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.