Reputation: 713
newb here.
I am trying to understand how to write a timer to close my c# console applications so that I don't have to hit 'return' again to close the window (i've been using Console.Read(); to keep it open so i can see that the app ran as intended thus far) So i'm trying to make a small timer method, below is what i've found the far, but it doesn't run as I don't understand what/how to handle it I think.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lec044b_ForLoop_Sum
{
class Program
{
public void Play()
{
Console.WriteLine("Announce Program");
Console.WriteLine("Close Program Announcement");
timer1_Tick(3000);
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Close();
}
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
}
}
}
I have researched this some, i've gone to the microsoft resources which are written for people who understand this stuff verses newbies and looked at a few blogs and just gotten more and more confused. Hoping for some help, which is appreciated kindly.
To sum up - i just want my console window to close automatically after 5 seconds. That is what i'm trying to do with a simple method. Ultimately I'll try to do this as a class or something, but i need to go in small steps so i understand.
Cheers
Upvotes: 2
Views: 16671
Reputation: 1
The post with the check is the correct answer. HOWEVER, I just wanted to be clear to use System.Threading.Timer! There is a System.Timers.Timer and a System.Windows.Forms.Timer I had a similar issue and the only one that worked perfectly for me WITHOUT locking up the UI was System.Threading.Timer My implementation of this is below.
using System.Threading;
System.Threading.Timer timer = new System.Threading.Timer(timerC, null, 5000, 5000);
private void timerC(object state)
{
Environment.Exit(0);
}
Upvotes: 0
Reputation: 25
Timer t = new Timer() ;
t.Interval = 120000;
t.Tick += (s, e) =>
{
Application.Exit();
};
t.Start();
Upvotes: 0
Reputation:
I believe this should do:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lec044b_ForLoop_Sum
{
class Program
{
public void Play()
{
Console.WriteLine("Announce Program");
Console.WriteLine("Close Program Announcement");
Timer t = new Timer(timerC, null, 5000, 5000);
}
private void timerC(object state)
{
Environment.Exit(0);
}
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.ReadLine();
}
}
}
(note how it's not the Timer
class from the namespace System.Timers
, it's from the namespace System.Threading
)
Upvotes: 3
Reputation: 2984
Thread.Sleep will do what u want:
static void Main(string[] args)
{
Play();
}
static void Play()
{
Console.WriteLine("Announce Program");
Console.WriteLine("Close Program Announcement");
Thread.Sleep(5000);
}
Upvotes: 8