Timer to close the application

前端 未结 7 1806
离开以前
离开以前 2021-01-12 02:40

How to make a timer which forces the application to close at a specified time in C#? I have something like this:

void  myTimer_Elapsed(object sender, System.         


        
7条回答
  •  隐瞒了意图╮
    2021-01-12 03:17

    If I understand your request, it seems a little wasteful to have a timer check the time every second, where you can do something like this:

    void Main()
    {
        //If the calling context is important (for example in GUI applications)
        //you'd might want to save the Synchronization Context 
        //for example: context = SynchronizationContext.Current 
        //and use if in the lambda below e.g. s => context.Post(s => this.Close(), null)
    
        var timer = new System.Threading.Timer(
                    s => this.Close(), null, CalcMsToHour(23, 00, 00), Timeout.Infinite);
    }
    
    int CalcMsToHour(int hour, int minute, int second)
    {
        var now = DateTime.Now;
        var due = new DateTime(now.Year, now.Month, now.Day, hour, minute, second);
        if (now > due)
            due.AddDays(1);
        var ms =  (due - now).TotalMilliseconds;
        return (int)ms;
    }
    

提交回复
热议问题