秒表时间耗尽零

Web*_*olf 0 c# asp.net-mvc

我有两个动作在mvc和一个我开始一个全球秒表而在另一个我停止它,但无论时间流逝多久,经过的时间总是0.这两个事件都是由按钮点击触发的.我的怀疑是按钮的帖子弄乱了我的时间过去了吗?如果有的话有什么方法吗?

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");
        }
Run Code Online (Sandbox Code Playgroud)

Ian*_*cer 5

它与StopWatch不同 - 为每个请求重新创建控制器.你需要在某个地方坚持秒表.

您可以将开始时间保持在一个static Dictionary<int,DateTimeOffset>映射workId到开始时间的开始时间.

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");
}
Run Code Online (Sandbox Code Playgroud)

但是这仍然不是很好,因为IIS之间的应用程序可能会重新启动,您将失去启动值.当不再需要值时,它也没有代码来清理表.您可以通过使用.NET Cache来改进后者,但是您确实需要一个数据库才能正确执行此操作.