user3839950
user3839950

Reputation: 23

How to make windows service request wait until the previous request is complete

I am working on a window services application and my window service will call one of the web services in certain intervals (for example 3 min). From the web service I will get data from a database and using that data I will send an email.

If I am having huge sets of rows in my db table it will take some time to send the mail. Here I have the problem: The window services send the first request and it will handle some set of records. So, while processing it by the web service, the window service sends another request to the web service before it has completed the first request. Due to this, the web service gets the same records from db again and again whenever it receives a new request from the windows service.

Can any one suggest me how to lock the previous request until it completes its work or some other way to handle this situation?

Web Service call:

protected override void OnStart(string[] args) 
{ 
   timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); 
   timer.Interval = 180000; 
   timer.AutoReset = false; 
   timer.Enabled = true; 
}

Inside Method

        using (MailWebService call = new MailWebService())
        {

            try
            {
                call.ServiceUrl = GetWebServiceUrl();
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                call.CheckMailQueue();


            }
            catch (Exception ex)
            {
                LogHelper.LogWriter(ex);
            }
            finally 
            {

            }
        }

Upvotes: 1

Views: 3211

Answers (1)

Mike Hixson
Mike Hixson

Reputation: 5189

The Monitor class works great for this scenario. Here is an example of how to use it:

// This is the object that we lock to control access
private static object _intervalSync = new object();

private void OnElapsedTime(object sender, ElapsedEventArgs e)
{       

    if (System.Threading.Monitor.TryEnter(_intervalSync))
    {
        try
        {
            // Your code here
        }
        finally
        {
            // Make sure Exit is always called
            System.Threading.Monitor.Exit(_intervalSync);
        }
    }
    else
    {
        //Previous interval is still in progress.
    }
}

There is also an overload for TryEnter that allows you to specify timeout for entering the section.

Upvotes: 5

Related Questions