How can I programmatically close the WinForms application after a certain time?

I start my form in the usual way:

Application.Run(new MainForm());

I want it to open and run before a certain time, and then close. I tried the following, but to no avail:

(1) In the main method (there was an expression Application.Run ()), I enter the following AFTER Application.Run ()

while (DateTime.Now < Configs.EndService) { }

RESULT: he never hits.

(2) BEFORE STARTING Application.Run () I am launching a new background theme:

        var thread = new Thread(() => EndServiceThread()) { IsBackground = true };
        thread.Start();

where EndServiceThread:

    public static void EndServiceThread()
    {
        while (DateTime.Now < Configs.EndService) { }
        Environment.Exit(0);
    }

RESULT: vshost32.exe has stopped working with a failure.

(3) In the MainForm Tick event:

        if (DateTime.Now > Configs.EndService)
        {
            this.Close();
            //Environment.Exit(0);
        }

RESULT: vshost32.exe has stopped working with a failure.

What is the right way to achieve my goal? Again, I want to run the form, open it and run until a certain time (Configs.EndService), and then close.

Thanks Ben.

+5
source share
4 answers

Timer .

, , 10 . 60 000 . :

void TimerTick(object sender)
{
    this.Close();
}

, , DateTime.Now .

, TimerTick . , Form.Close , . . , .

, , , Form.Invoke Close.

WaitableTimer . Framework WaitableTimer, . . .NET #. http://www.mischel.com/pubs/waitabletimer.zip

WaitableTimer, , . Invoke :

this.Invoke((MethodInvoker) delegate { this.Close(); });
+4

- :

public partial class Form1 : Form
{
    private static Timer _timer = new Timer();

    public Form1()
    {
        InitializeComponent();
        _timer.Tick += _timer_Tick;
        _timer.Interval = 5000; // 5 seconds
        _timer.Start();            
    }

    void _timer_Tick(object sender, EventArgs e)
    {
        // Exit the App here ....
        Application.Exit();
    }
}
+2

"ServiceEnded"? , , .

0

If you use System.Threading.Timer, you can use DueTimeto install the first time it starts, like the time when you want to close the application

new System.Threading.Timer((o) => Application.Exit(), null, (Configs.EndService - DateTime.Now), TimeSpan.FromSeconds(0));
Application.Run(new Form1());
0
source

All Articles