Get elapsed time since application start

2020-03-01 05:27发布

问题:

I am porting an app from ActionScript3.0 (Flex) to C# (WPF).AS3.0 has got a handy utility called getTimer() which returns time since Flash Virtual machine start in milliseconds.I was searching in C# through classes as

DateTime
DispatcherTimer
System.Diagnostics.Process
System.Diagnostics.Stopwatch

but found nothing like this.It seems a very basic feature to me.For example Unity3D which runs on Mono has something familiar. Do I miss some utility here?

Thanks in advance.

回答1:

Process.GetCurrentProcess().StartTime is your friend.

..so to get elapsed time since start:

DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()

alternatively, if you need more definition, System.Diagnostics.Stopwatch might be preferable. If so, start a stopwatch when your app starts:

Stopwatch sw = Stopwatch.StartNew();

then query the sw.Elapsed property during your execution run.



标签: c# .net wpf timer