Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active April 26, 2022 10:03
Show Gist options
  • Save relyky/cb44bc83f3a94b693b618d6e74c47063 to your computer and use it in GitHub Desktop.
Save relyky/cb44bc83f3a94b693b618d6e74c47063 to your computer and use it in GitHub Desktop.
C#, Timer, Stopwatch, 精確計時器
/// 精確計時器
/// ref→[Stopwatch 類別](https://docs.microsoft.com/zh-tw/dotnet/api/system.diagnostics.stopwatch?view=net-6.0)
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
///
/// ref→[System.Thread.Timer](https://msdn.microsoft.com/zh-tw/library/system.threading.timer.aspx)
/// 當 timer 觸發時,以新的thread執行,為多執行緒。適合沒有UI的狀況。
///
/// .Net Framework 提供三種timer:
/// * System.Timers.Timer
/// * System.Threading.Timer
/// * System.Windows.Forms.Timer
/// 在此文章有討論[執行緒定時器](https://dotblogs.com.tw/yc421206/2011/01/30/21141)
///
/// 此例應用於 windows service
///
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace MyWindowsService
{
public partial class MainService : ServiceBase
{
private System.Threading.Timer _timer = null;
private readonly object _thisLock = new object(); // used to lock for synchronization
private readonly object _timerLock = new object();
public MainService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Debug.WriteLine("OnStart");
MyState state = new MyState();
_timer = new System.Threading.Timer(MyTimerCallback, state, 1000, 1000);
}
protected override void OnStop()
{
Debug.WriteLine("OnStop");
_timer.Dispose();
}
/// <summary>
/// TimerCallback, This method is called by the timer delegate.
/// </summary>
public void MyTimerCallback(Object stateInfo)
{
lock(_timerLock) // 若有同步需求就需lock。
{
MyState state = (MyState)stateInfo;
state.steps++;
Debug.WriteLine("{0} {1:HH:mm:ss} {2}", "MyTimerCallback", DateTime.Now, state.steps);
// 模擬執行時間差異性:模數為4時模擬跑3秒才完成,否則立即完成。
if(state.steps % 4 == 0)
Thread.Sleep(3000);
Debug.WriteLine("{0} {1:HH:mm:ss} {2}", "Sleep", DateTime.Now, state.steps);
}
}
}
internal class MyState
{
public int steps = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment