在一段时间后以编程方式关闭WinForms应用程序的正确方法是什么?

Ben*_*Ben 5 c# winforms

我以通常的方式开始我的表单:

Application.Run(new MainForm());
Run Code Online (Sandbox Code Playgroud)

我希望它打开并运行到一定时间,然后关闭.我尝试了以下但无济于事:

(1)在Main方法中(是Application.Run()语句是),我输入以下AFTER Application.Run()

while (DateTime.Now < Configs.EndService) { }
Run Code Online (Sandbox Code Playgroud)

结果:它永远不会被击中.

(2)在Application.Run()之前我启动一个新的后台线程:

        var thread = new Thread(() => EndServiceThread()) { IsBackground = true };
        thread.Start();
Run Code Online (Sandbox Code Playgroud)

其中EndServiceThread是:

    public static void EndServiceThread()
    {
        while (DateTime.Now < Configs.EndService) { }
        Environment.Exit(0);
    }
Run Code Online (Sandbox Code Playgroud)

结果:vshost32.exe已停止工作崩溃.

(3)在MainForm Tick事件中:

        if (DateTime.Now > Configs.EndService)
        {
            this.Close();
            //Environment.Exit(0);
        }
Run Code Online (Sandbox Code Playgroud)

结果:vshost32.exe已停止工作崩溃.

实现目标的正确方法是什么?再次,我想启动表单,让它打开并运行到一定时间(Configs.EndService),然后关闭.

谢谢你,本.

Jim*_*hel 5

创建一个Timer,并使其在其事件处理程序中关闭程序。

假设您希望应用程序在10分钟后关闭。您以60,000毫秒的周期初始化计时器。您的事件处理程序将变为:

void TimerTick(object sender)
{
    this.Close();
}
Run Code Online (Sandbox Code Playgroud)

如果您希望它在特定的日期和时间关闭,您可以让计时器每秒滴答一次,然后检查DateTime.Now所需的结束时间。

这将起作用,因为TimerTick将在UI线程上执行。您的单独线程概念的问题Form.Close是在后台线程而不是 UI线程上调用的。这引发了异常。与UI元素进行交互时,它必须位于UI线程上。

如果调用Form.Invoke执行,您的后台线程想法可能会起作用Close

您还可以创建一个WaitableTimer对象并在特定时间设置其事件。该框架没有WaitableTimer,但是一个可用。请参阅文章使用C#的.NET中的等待计时器。可以在http://www.mischel.com/pubs/waitabletimer.zip中找到代码

如果使用WaitableTimer,则建议回调在后台线程上执行。您必须Invoke与UI线程同步:

this.Invoke((MethodInvoker) delegate { this.Close(); });
Run Code Online (Sandbox Code Playgroud)