繁体   English   中英

秒表经过的时间为零

[英]Stopwatch Time Elapsed Zero

我在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");
        }

这与StopWatch不同-控制器是为每个请求重新创建的。 您需要将秒表保持在某个地方。

您可以将开始时间保存在static Dictionary<int,DateTimeOffset> ,该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");
}

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

如果您想为所有会话共享同一实例 (通常不希望这样做),只需将其标记为静态,

private static Stopwatch stopwatch = new Stopwatch();

同样,如果无法从其他控制器/部件访问它,则不必将其定义为公共。

正如@Ian Mercer所建议的那样,这不是用于秒表的好方法。

看一下这些链接:

访问修饰符

静态C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM