简体   繁体   English

测量按钮1单击和按钮2单击之间的时间

[英]Measuring time between button 1 click and button 2 click

I need to measure the time between button 1 click and button 2 click. 我需要测量按钮1单击和按钮2单击之间的时间。 I know that I can use Datetime.Now but any variable I assign, I can only use in one eventhandler. 我知道我可以使用Datetime.Now但是我分配的任何变量都只能在一个事件处理程序中使用。 I searched on the internet but all i could find was using a stopwatch, but that doesn't seem to work anymore in Visual Studio 2017. 我在互联网上进行搜索,但我能找到的只是使用秒表,但这在Visual Studio 2017中似乎不再起作用。

You can use a Stopwatch instance or DateTime calculation. 您可以使用秒表实例或DateTime计算。 If you want to use Stopwatch you also have to import the containing namespace. 如果要使用秒表,则还必须导入包含名称空间。

using System.Diagnostics;

Either way, you have to put your variable in a scope above the eventhandlers so that both eventhandlers have access to it. 无论哪种方式,都必须将变量放在事件处理程序上方的作用域中,以便两个事件处理程序都可以访问它。 Here is a Winforms example that uses both methods, but it can easily be translated to other scenarios. 这是同时使用这两种方法的Winforms示例,但是可以轻松地将其转换为其他方案。

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
    public partial class Form1 : Form {
        private DateTime from;
        private Stopwatch watch = new Stopwatch();

        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            from = DateTime.Now;
            watch.Restart();
        }

        private void button2_Click(object sender, EventArgs e) {
            watch.Stop();
            MessageBox.Show(
                "Date subtraction: " + DateTime.Now.Subtract(from).ToString() + Environment.NewLine +
                "Stopwatch: " + watch.Elapsed.ToString());

        }
    }
}

Use Stopwatch 使用Stopwatch

Stopwatch _sw = new Stopwatch();

void Button1_Click(sender, e)
{
    if (_sw.IsRunning) 
        _sw.Stop();
    _sw.Reset();
    _sw.Start();
}


void Button2_Click(sender, e)
{
    if (_sw.IsRunning)   
        _sw.Stop();
    MessageBox.Show(_sw.Elapsed);
}

If you in Web Forms, you can stuff your stop watch into Session . 如果您使用的是Web表单,则可以将秒表塞入Session And in REST, well, you can use runtime caching. 在REST中,您可以使用运行时缓存。

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

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