Milliseconds in DateTime.Now on .NET Compact Framework always zero?

岁酱吖の 提交于 2019-12-04 01:56:52

Environment.TickCount will return the number of milliseconds that Windows (or Windows Mobile) has been running since the last reboot.

To use this, add these two form-level variables to your code:

private DateTime _start;
private int _startTick;

In your form's Load event, do this:

private void Form1_Load(object sender, EventArgs e)
{
    _start = DateTime.Now;
    _startTick = Environment.TickCount;
}

Whenever you need a DateTime object with milliseconds, do this:

DateTime timeStamp = 
    _start.AddMilliseconds(Environment.TickCount - _startTick);

Environment.TickCount is an int and this value will "wrap around" to Int32.MinValue after 25 days or so. If your device is going to be running that long without restarting, you'll want to add a check for an Environment.TickCount value that is less than the last value read, and reset both _start and _startTick if so.

What about the High Resolution Timer?

The main alternative is the System.Diagnostics.Stopwatch class.

It is available in CE but note the IsHighResolution property. It probably is False on your device but do check.

It is as accurate as you're going to get without P/Invoke.

In regular framework v2.0 you may use DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") to get miliseconds. More f means more precision.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!