I start my form in the usual way:
Application.Run(new MainForm());
I want it to open and run until a certain time, then close. I\'ve tried
Create a Timer, and have it close the program in its event handler.
Say you want the application to shut down after 10 minutes. You initialize the timer with a period of 60,000 milliseconds. Your event handler becomes:
void TimerTick(object sender)
{
this.Close();
}
If you want it to close at a specific date and time, you can have the timer tick once per second, and check DateTime.Now
against the desired end time.
This will work because the TimerTick
will execute on the UI thread. The problem with your separate thread idea was that Form.Close
was called on a background thread, not the UI thread. That throws an exception. When you interact with UI elements, it has to be on the UI thread.
Your background thread idea probably would work if you called Form.Invoke
to execute the Close
.
You could also create a WaitableTimer
object and set its event for the specific time. The Framework doesn't have a WaitableTimer
, but one is available. See the article Waitable Timers in .NET with C#. Code is available at http://www.mischel.com/pubs/waitabletimer.zip
If you use the WaitableTimer
, be advised that the callback executes on a background thread. You'll have to Invoke
to synchronize with the UI thread:
this.Invoke((MethodInvoker) delegate { this.Close(); });
How about something like this:
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();
}
}
If you use the System.Threading.Timer
you can use the DueTime
to set the first time it fires as the time you want to close your application
new System.Threading.Timer((o) => Application.Exit(), null, (Configs.EndService - DateTime.Now), TimeSpan.FromSeconds(0));
Application.Run(new Form1());
Is there "ServiceEnded" event? If yes close your form when your service ended.