【发布时间】:2016-06-14 14:12:05
【问题描述】:
我正在将一个以 50 毫秒(用于串行通信)轮询的 Windows C# 应用程序移植到 Linux(使用 Mono)。我们目前正在使用 ZylTimer(由 ZylSoft 提供)在每个时间间隔生成“tick”事件,但是由于该库将 pInvoke 调用包装到 windows 多媒体库,我们当然不能使用它。
//i.e.
timZylComms.Tick += new ZylTimer.TickEventHandler(timZylComms_Tick);
timTimeout.Tick += new ZylTimer.TickEventHandler(timTimeout_Tick);
所以,这让我问是否存在我可以在 Mono 下使用的替代方案? 最好的方法是使用 Tick 事件扩展“秒表”类(以高分辨率计算)吗?
或者是否有任何我可以包装的 linux 库来重现此功能? 还是有其他方法可以实现这一目标?
感谢您对此的任何想法。
编辑: 这样做会有什么问题吗:
internal class LinuxHiResTimer{
internal event EventHandler Tick;
private System.Diagnostics.Stopwatch watch;
internal int Interval{ get; set;}
private bool enabled;
internal bool Enabled {
get{ return enabled; }
set {
if (value) {
watch.Start ();
Task.Run (tickGenerator);
enabled = value;
} else {
enabled = value;
}
}
}
private async Task tickGenerator(){
while (enabled){
if (watch.ElapsedMilliseconds > Interval) {
watch.Reset ();
if (Tick != null)
Tick (this, new EventArgs ());
} else {
float fWaitPeriod = (float)(0.8 * (Interval - watch.ElapsedMilliseconds));
if (fWaitPeriod>20)
await Task.Delay(TimeSpan.FromMilliseconds(fWaitPeriod));
}
}
watch.Stop ();
}
internal LinuxHiResTimer(){
watch = new Stopwatch ();
}
~LinuxHiResTimer(){
watch.Stop ();
}
}
【问题讨论】:
-
有没有办法包装 POSIX clock_gettime() 来实现这一点?
-
使用 System.Diagnostics.Stopwatch stackoverflow.com/questions/7736013/…
-
@rytis-i 秒表没有 tick() 方法。最好的方法是使用 Tick 事件扩展“秒表”类(以高分辨率计算)吗?