Timer in windows Service C# Finish before the task ended

عبدالمجيد العتيبي 41 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 for business | Windows Client for IT Pros | User experience | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    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.