Reputation: 6326
I have two actions in mvc and in one I start a global stopwatch and in another I stop it, but the time elapsed is always 0 no matter how long the time elapsed is. Both of these events are triggered by button clicks. My suspition is that the post of the button is messing with my time elapsed maybe? If so is there any way around this?
public Stopwatch stopwatch = new Stopwatch();
public ActionResult Start()
{
stopwatch.Start();
return RedirectToAction("Index");
}
public ActionResult Stop(int workid)
{
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
int hours = ts.Hours;
int mins = ts.Minutes;
using (ZDevContext db = new ZDevContext())
{
DashboardHelper dashhelper = new DashboardHelper(db);
dashhelper.RecordTimeSpent(workid, hours, mins);
}
return View("Index");
}
Upvotes: 0
Views: 997
Reputation: 5729
if you want to make the same instance shared for all sessions (which you usually don't want) just mark it as static,
private static Stopwatch stopwatch = new Stopwatch();
also, you don't have to define it as public if it will not be accessible from other controllers/assemblies.
as @Ian Mercer suggested, it is not a good way to use for a stopwatch.
have a look at these links:
Upvotes: 2
Reputation: 39277
It's not the same StopWatch - the controller is created anew for each request. You would need to persist the stopwatch somewhere.
You could persist the start time in a static Dictionary<int,DateTimeOffset>
which would map a workId
to the started time.
static ConcurrentDictionary<int,DateTimeOffset> starts = new ConcurrentDictionary<int,DateTimeOffset>();
public ActionResult Start(int workId)
{
starts.TryAdd(workId, DateTimeOffset.Now);
return RedirectToAction("Index");
}
public ActionResult Stop(int workId)
{
DateTimeOffset started = DateTimeOffset.MinValue;
if (starts.TryGet(workId, out started))
{
// calculate time difference
}
return View("Index");
}
But this still isn't great as your application may be restarted by IIS in between and you will lose the starts value. It also has no code to clean the table when a value is no longer needed. You could improve the latter by using the .NET Cache but you really need a database to do this right.
Upvotes: 5