6

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

Application.Run(new MainForm());

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

(1) 在 Main 方法中(Application.Run() 语句是),我在 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),然后关闭。

谢谢你,本。

4

4 回答 4

5

创建一个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 中的等待计时器一文。代码可在http://www.mischel.com/pubs/waitabletimer.zip

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

this.Invoke((MethodInvoker) delegate { this.Close(); });
于 2013-03-19T03:21:33.237 回答
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();
    }
}
于 2013-03-19T03:34:53.227 回答
0

是否有“ServiceEnded”事件?如果是,请在您的服务结束时关闭您的表格。

于 2013-03-19T03:31:55.883 回答
0

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

new System.Threading.Timer((o) => Application.Exit(), null, (Configs.EndService - DateTime.Now), TimeSpan.FromSeconds(0));
Application.Run(new Form1());
于 2013-03-19T03:39:14.923 回答