简体   繁体   English

System.Timer同步不起作用

[英]System.Timer synchronization not working

I have created a windows service which will fire an event every T interval. 我创建了一个Windows服务,该服务将在每个T间隔触发一个事件。 This event will consume a web service and call its web method. 此事件将使用Web服务并调用其Web方法。 This windows service has no idea how long will the web method take to complete the execution. Windows服务不知道Web方法将花费多长时间来完成执行。

What I am seeing is when interval is over, multiple instances of web method is running.I am using counters but it is not working. 我看到的是,当间隔结束时,Web方法的多个实例正在运行。我正在使用计数器,但无法正常工作。 I don't want overlapping of web method execution. 我不想重叠执行Web方法。

    public partial class AutoAllocation: ServiceBase
    {
        private Timer timer = null;
        private bool runningCounter=false;
        public AutoAllocation()
        {
            InitializeComponent();
        }

 protected override void OnStart(string[] args)
        {
            timer = new Timer();
            string timerInterval = ConfigurationManager.AppSettings["TimeInterval"];
            timer.Interval = Convert.ToDouble(timerInterval);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerTick);
            timer.Enabled = true;            
        }

        private void TimerTick(object sender, ElapsedEventArgs e)
        {
            if (runningCounter == false)
            {
                runningCounter = true;
                EmployeeManagementService resourceMgmt = new EmployeeManagementService ();

                resourceMgmt.AutoAllocateSalary();
                runningCounter = false;
                }
        }

Try setting AutoReset to false. 尝试将自动重置设置为false。

This means the timer will fire once and won't fire again until you manually start it again, which you can do after your webservice call. 这意味着计时器将触发一次,直到您再次手动启动它后才会再次触发,您可以在调用网络服务后执行此操作。

For example: 例如:

    protected override void OnStart(string[] args)
    {           
        string timerInterval = ConfigurationManager.AppSettings["TimeInterval"];

        timer = new Timer();
        timer.AutoReset = false;
        timer.Interval = Convert.ToDouble(timerInterval);
        timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerTick);
        timer.Start();          
    }

    private void TimerTick(object sender, ElapsedEventArgs e)
    {
        EmployeeManagementService resourceMgmt = new EmployeeManagementService ();

        resourceMgmt.AutoAllocateSalary();

        ((Timer)sender).Start();
    }

This will stop any overlapping of calls, which is probably what's going on here. 这将停止任何重叠的呼叫,这可能就是这里发生的情况。

Also remember that the interval is in milliseconds so if you're supplying seconds make sure its *1000 . 还要记住,时间间隔以毫秒为单位,因此,如果要提供秒数,请确保其*1000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM