Search code examples
c#asp.netstopwatch

stopwatch time per user in c# asp.net mvc application


I have a set of users in my asp.net mvc application.

When any user start stopwatch then i need stopwatch to continue even after user logout. And run it until he does not login again and click stop.

i can start it on start button click

        stopWatch = new Stopwatch();
        stopWatch.Start();

But how can i track it against user? so that after the user logout and then login he will see the elapsed time including the time he was not active in the app?

so after the user login and click stop watch he should get the elapsed time including the whole time.

TimeSpan ts = stopWatch.Elapsed;

is it better to use angular directive/javascript timer?


Solution

  • Why use a Stopwatch for something like that? Stopwatch is designed to provide high-resolution time measurements, I doubt your user needs to know the exact time down to a few nano-seconds...
    From MSDN:

    Provides a set of methods and properties that you can use to accurately measure elapsed time.

    Simply save the DateTime.Now(), the state of the button (i.e start, stop) and the user id, and then when the user with the same id press that button again just calculate the time differences.

    TimeSpan elapsedTime = FirstClickDateTime - SecondClickDateTime;
    

    Then all you have to do is format the display of the TimeSpan object.