简体   繁体   English

如何暂停计时器直到 C# 中的程序完成

[英]How to pause timer till procedure within finishes in C#

I am building a service.我正在建立一个服务。

This service process and move files from one forlder to another.此服务处理并将文件从一个文件夹移动到另一个文件夹。

There is a timer in this service that check every minute to see if there are files to move and move them该服务中有一个计时器,每分钟检查一次是否有文件要移动并移动它们

what is happening is when it starts it moves the files but if the number of files is big it takes more than 1 minute which leads to call the same procedure again and get errors发生的事情是它启动时会移动文件,但如果文件数量很大,则需要超过 1 分钟,这会导致再次调用相同的过程并出现错误

I want the timer to be paused till the function within finishes then back again我希望计时器暂停,直到 function 完成然后再返回

here is my code这是我的代码

    protected override void OnStart(string[] args)
    {

            Timer timer = new Timer();
            timer.Interval = IntervalLength;
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Start();
    }

    public void OnTimer(object sender, ElapsedEventArgs args)
    {
        this.Stop();

        DO();

        this.Start();

    }

    private void DO()
    {
     //Process and move files
    }

I added Stop to stop the timer but Start() is give this error我添加了 Stop 来停止计时器,但 Start() 给出了这个错误

Severity Code Description Project File Line Suppression State Error CS1061 'XMI2DBSrv' does not contain a definition for 'Start' and no accessible extension method 'Start' accepting a first argument of type 'XMI2DBSrv' could be found (are you missing a using directive or an assembly reference?) XMI2DB E:\XMI2DBsrv.cs 73 Active严重性代码 描述 项目文件行抑制 State 错误 CS1061 'XMI2DBSrv' 不包含“Start”的定义,并且找不到接受“XMI2DBSrv”类型的第一个参数的可访问扩展方法“Start”(您是否缺少 using 指令或程序集参考?) XMI2DB E:\XMI2DBsrv.cs 73 活动

how to do that?怎么做?

In your OnTimer method, you are using this .在您的OnTimer方法中,您正在使用this However this refers to the class that contains the method, rather than the Timer object.但是, this是指包含该方法的 class,而不是 Timer object。

You need to call Start and Stop on the Timer object, which is sender in this case.您需要在计时器 object 上调用 Start 和 Stop,在这种情况下它是sender

Therefore, what you are looking for is ((Timer)sender).Start();因此,您正在寻找的是((Timer)sender).Start(); . .

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

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