就在这个 - 你怎么一个计时器添加到C#控制台应用程序? 这将是巨大的,如果你能提供一些例子编码。
Answer 1:
这是非常好的,但为了模拟一些时间的推移,我们需要运行需要一些时间的命令,这就是在第二个例子很清楚。
但是,使用一个for循环做一些功能性的风格永远需要大量的设备资源,相反,我们可以使用垃圾收集器做这样一些事情。
我们可以看到在这个代码修改从同一本书CLR通过C#第三版。
using System;
using System.Threading;
public static class Program {
public static void Main() {
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o) {
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}
Answer 2:
使用System.Threading.Timer类。
System.Windows.Forms.Timer是主要设计用于在单个线程使用的通常是Windows窗体UI线程。
还有在.NET框架的发展增添早在System.Timers类。 但是一般建议使用System.Threading.Timer类,而不是因为这仅仅是围绕System.Threading.Timer的包装呢。
此外,还建议始终使用静态(在VB.NET共享)System.Threading.Timer如果您正在开发一个Windows服务,需要一个计时器定期运行。 这将避免你的计时器对象的可能过早垃圾收集。
下面是一个控制台应用程序定时器的例子:
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
Console.WriteLine("Main thread: starting a timer");
Timer t = new Timer(ComputeBoundOp, 5, 0, 2000);
Console.WriteLine("Main thread: Doing other work here...");
Thread.Sleep(10000); // Simulating other work (10 seconds)
t.Dispose(); // Cancel the timer now
}
// This method's signature must match the TimerCallback delegate
private static void ComputeBoundOp(Object state)
{
// This method is executed by a thread pool thread
Console.WriteLine("In ComputeBoundOp: state={0}", state);
Thread.Sleep(1000); // Simulates other work (1 second)
// When this method returns, the thread goes back
// to the pool and waits for another task
}
}
从书CLR通过C#由杰夫·里克特。 通过这本书介绍了第23章3种类型的定时器背后的基本原理的方式,强烈推荐。
Answer 3:
下面是创建一个简单的秒计时器滴答代码:
using System;
using System.Threading;
class TimerExample
{
static public void Tick(Object stateInfo)
{
Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
}
static void Main()
{
TimerCallback callback = new TimerCallback(Tick);
Console.WriteLine("Creating timer: {0}\n",
DateTime.Now.ToString("h:mm:ss"));
// create a one second timer tick
Timer stateTimer = new Timer(callback, null, 0, 1000);
// loop here forever
for (; ; )
{
// add a sleep for 100 mSec to reduce CPU usage
Thread.Sleep(100);
}
}
}
这里是输出结果:
c:\temp>timer.exe
Creating timer: 5:22:40
Tick: 5:22:40
Tick: 5:22:41
Tick: 5:22:42
Tick: 5:22:43
Tick: 5:22:44
Tick: 5:22:45
Tick: 5:22:46
Tick: 5:22:47
编辑:这是不是一个好主意,以增加硬旋循环放入代码,因为他们消耗为没有获取的CPU周期。 在这种情况下,刚添加的循环停止关闭应用程序,允许观察线程的行为。 但为求正确的,并降低CPU使用率一个简单的睡眠通话加入这个循环。
Answer 4:
让我们有一点乐趣
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 10;
static void Main(string[] args)
{
timer.Elapsed+=timer_Elapsed;
timer.Start();
Console.Read();
}
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
Console.Clear();
Console.WriteLine("=================================================");
Console.WriteLine(" DIFFUSE THE BOMB");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" B O O O O O M M M M M ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" G A M E O V E R");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}
}
}
Answer 5:
或者使用的Rx,简短而亲切:
static void Main()
{
Observable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine("I am called... {0}", t));
for (; ; ) { }
}
Answer 6:
您也可以使用自己的计时机制,如果你想要更多的控制,但可能不太准确度和更多的代码/复杂性,但我还是希望推荐一个计时器。 如果你需要有比实际时间线程控制使用这虽然:
private void ThreadLoop(object callback)
{
while(true)
{
((Delegate) callback).DynamicInvoke(null);
Thread.Sleep(5000);
}
}
将你的时间线(修改该停止的时候reqiuired,在任何你想要的时间间隔)。
并使用/开始你可以这样做:
Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));
t.Start((Action)CallBack);
回调是你要叫在每个区间的空白参数方法。 例如:
private void CallBack()
{
//Do Something.
}
Answer 7:
您也可以创建自己的(如果不满意,可用的选项)。
创建自己的Timer
实现是非常基本的东西。
这是一个需要在同一线程作为我的基本代码的其余部分对COM对象访问的应用程序的例子。
/// <summary>
/// Internal timer for window.setTimeout() and window.setInterval().
/// This is to ensure that async calls always run on the same thread.
/// </summary>
public class Timer : IDisposable {
public void Tick()
{
if (Enabled && Environment.TickCount >= nextTick)
{
Callback.Invoke(this, null);
nextTick = Environment.TickCount + Interval;
}
}
private int nextTick = 0;
public void Start()
{
this.Enabled = true;
Interval = interval;
}
public void Stop()
{
this.Enabled = false;
}
public event EventHandler Callback;
public bool Enabled = false;
private int interval = 1000;
public int Interval
{
get { return interval; }
set { interval = value; nextTick = Environment.TickCount + interval; }
}
public void Dispose()
{
this.Callback = null;
this.Stop();
}
}
您可以添加事件如下:
Timer timer = new Timer();
timer.Callback += delegate
{
if (once) { timer.Enabled = false; }
Callback.execute(callbackId, args);
};
timer.Enabled = true;
timer.Interval = ms;
timer.Start();
Window.timers.Add(Environment.TickCount, timer);
为了确保计时器工作,你需要按照以下步骤创建一个无限循环:
while (true) {
// Create a new list in case a new timer
// is added/removed during a callback.
foreach (Timer timer in new List<Timer>(timers.Values))
{
timer.Tick();
}
}