繁体   English   中英

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

[英]What is the proper way to programmatically close a WinForms application after a certain time?

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

Application.Run(new MainForm());

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

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

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

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

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

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

其中EndServiceThread是:

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

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

(3)在MainForm Tick事件中:

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

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

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

谢谢你,本。

创建一个Timer ,让它在事件处理程序中关闭程序。

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

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

如果您希望它在特定日期和时间关闭,您可以让计时器每秒打勾一次,并根据所需的结束时间检查DateTime.Now

这将起作用,因为TimerTick将在UI线程上执行。 您的单独线程想法的问题是Form.Close是在后台线程上调用的, 而不是在UI线程上调用的。 这引发了一个例外。 当您与UI元素交互时,它必须位于UI线程上。

如果您调用Form.Invoke来执行Close那么您的后台线程概念可能会起作用。

您还可以创建WaitableTimer对象并在特定时间设置其事件。 框架没有WaitableTimer ,但有一个可用。 请参阅使用C#在.NET中使用Waitable Timers一文。 代码可从http://www.mischel.com/pubs/waitabletimer.zip获得

如果使用WaitableTimer ,请注意回调在后台线程上执行。 您必须Invoke以与UI线程同步:

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

这样的事情怎么样:

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();
    }
}

有“ServiceEnded”活动吗? 如果是,请在服务结束时关闭您的表单。

如果您使用System.Threading.Timer您可以使用DueTime将其第一次触发时设置为您要关闭应用程序的时间

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

暂无
暂无

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

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