C#定时器(控制台应用程序)

C#定时器(控制台应用程序),c#,C#,我正在尝试为服务器创建一个测试其工作人员的程序,在该程序中,我需要一个计时器来知道他们回答所有问题所花的时间,该程序即将完成,我唯一需要的是一个计时器,我需要计时器从0开始计数,并在变量“TestFinished”为真时停止。 我找到了这个计时器,我试图让它从“OnTimedEvent”外部更改变量“Seconds”,但我做不到。有人能帮我吗 class Program { public static void Main() { System.Timers

我正在尝试为服务器创建一个测试其工作人员的程序,在该程序中,我需要一个计时器来知道他们回答所有问题所花的时间,该程序即将完成,我唯一需要的是一个计时器,我需要计时器从0开始计数,并在变量“TestFinished”为真时停止。 我找到了这个计时器,我试图让它从“OnTimedEvent”外部更改变量“Seconds”,但我做不到。有人能帮我吗

    class Program
{
    public static void Main()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 1000;
        aTimer.Enabled = true;

        int seconds = 0;
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
     seconds++;
    }
}

简单的方法是把它变成一个字段

class Program
{
    static int seconds = 0;
    public static void Main()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 1000;
        aTimer.Enabled = true;


        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
     seconds++;
    }
}
编辑:感谢@stuartd)要使代码编译,您必须在类范围内声明静态变量
seconds

class Program
{
    private static int seconds = 0;
    public static void Main()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 1000;
        aTimer.Enabled = true;

        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
     seconds++;
    }
}
2) 您可以使用秒表测量经过的时间:

var sw = StopWatch.StartNew();
sw.Stop();
sw.Elapsed.TotalSeconds;

计时器
不是很精确,不应用于测量时间,而应用于计划定期执行的代码

你应该用秒表来测量时间。这就是它的用途。只需在要测量的操作之前调用
Start()
,然后在操作完成后立即调用
Stop()
。然后,您可以以
滴答声
毫秒
时间跨度
的形式访问经过的时间

例如,假设您调用了某种类型的
Test
类来启动测试,您可以执行如下操作,即在管理测试之前启动秒表,然后在测试完成后立即停止秒表:

class StaffTest
{
    public List<QuizItem> QuizItems = new List<QuizItem>();
    public int Score { get; private set; }
    public double ScorePercent => (double)Score / QuizItems.Count * 100;
    public string Grade =>
        ScorePercent < 60 ? "F" :
        ScorePercent < 70 ? "D" :
        ScorePercent < 80 ? "C" :
        ScorePercent < 90 ? "B" : "A";
    public double ElapsedSeconds => stopwatch.Elapsed.TotalSeconds;

    private Stopwatch stopwatch = new Stopwatch();

    public void BeginTest()
    {
        stopwatch.Restart();

        for (int i = 0; i < QuizItems.Count; i++)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($"Question #{i + 1}: ");
            Console.ResetColor();

            if (QuizItems[i].AskQuestion()) Score++;

            Console.WriteLine();
        }

        stopwatch.Stop();
    }
}
有了这些类,管理测试变得非常简单。您只需创建一些
QuizItem
对象,然后调用
test.beginest()。剩下的工作已经完成,包括获取经过的时间

例如:

static void Main(string[] args)
{
    // Create a new test
    var test = new StaffTest
    {
        QuizItems = new List<QuizItem>
        {
            new QuizItem("What it the capital of Washington State?", 
                new List<string> {"Seattle", "Portland", "Olympia" }, 2),
            new QuizItem("What it the sum of 45 and 19?", 
                new List<string> {"64"}, 0),
            new QuizItem("Which creature is not a mammal?", 
                new List<string> {"Dolphin", "Shark", "Whale" }, 1)
        }
    };

    Console.Write("Press any key to start the test...");
    Console.ReadKey();
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine($"\n\n(Test started at {DateTime.Now})\n");
    Console.ResetColor();

    test.BeginTest();

    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine($"(Test ended at {DateTime.Now})\n");
    Console.ResetColor();

    Console.WriteLine($"Thank you for taking the test.\n");
    Console.WriteLine($"You scored ................ {test.Score} / {test.QuizItems.Count}");
    Console.WriteLine($"Your percent correct is ... {test.ScorePercent.ToString("N0")}%");
    Console.WriteLine($"Your grade is ............. {test.Grade}");
    Console.WriteLine($"The total time was ........ {test.ElapsedSeconds.ToString("N2")} seconds");

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
static void Main(字符串[]args)
{
//创建一个新的测试
var测试=新员工测试
{
QuizItems=新列表
{
new QuizItem(“华盛顿州的首都是什么?”,
新名单{“西雅图”、“波特兰”、“奥林匹亚”},2),
new QuizItem(“45和19的总和是多少?”,
新列表{“64”},0),
new QuizItem(“哪种生物不是哺乳动物?”,
新名单{“海豚”、“鲨鱼”、“鲸鱼”},1)
}
};
控制台。写入(“按任意键开始测试…”);
Console.ReadKey();
Console.ForegroundColor=ConsoleColor.Yellow;
WriteLine($”\n\n(测试在{DateTime.Now})开始)\n);
Console.ResetColor();
test.beginest();
Console.ForegroundColor=ConsoleColor.Yellow;
WriteLine($”(测试在{DateTime.Now}结束)\n);
Console.ResetColor();
Console.WriteLine($“感谢您参加测试。\n”);
Console.WriteLine($“您获得了………{test.Score}/{test.QuizItems.Count}”);
WriteLine($“您的正确率是…{test.ScorePercent.ToString(“N0”)}%”);
Console.WriteLine($“您的成绩是………{test.grade}”);
WriteLine($”总时间为…….{test.ElapsedSeconds.ToString(“N2”)}秒”);
控制台。写入(“\n完成!\n按任意键退出…”);
Console.ReadKey();
}
输出


这也许能回答您的问题你可以在这个问题中只留下
c#
标记,它不是一个全局变量,而是一个字段!谢谢,(不要介意这段文字,它只是为了让我发送信息)我已经测试了秒表,并将它与计时器进行了比较,结果有很大的不同,你是对的,计时器慢了,而且一点也不准确。谢谢你详细的回答和帮助。
static void Main(string[] args)
{
    // Create a new test
    var test = new StaffTest
    {
        QuizItems = new List<QuizItem>
        {
            new QuizItem("What it the capital of Washington State?", 
                new List<string> {"Seattle", "Portland", "Olympia" }, 2),
            new QuizItem("What it the sum of 45 and 19?", 
                new List<string> {"64"}, 0),
            new QuizItem("Which creature is not a mammal?", 
                new List<string> {"Dolphin", "Shark", "Whale" }, 1)
        }
    };

    Console.Write("Press any key to start the test...");
    Console.ReadKey();
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine($"\n\n(Test started at {DateTime.Now})\n");
    Console.ResetColor();

    test.BeginTest();

    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine($"(Test ended at {DateTime.Now})\n");
    Console.ResetColor();

    Console.WriteLine($"Thank you for taking the test.\n");
    Console.WriteLine($"You scored ................ {test.Score} / {test.QuizItems.Count}");
    Console.WriteLine($"Your percent correct is ... {test.ScorePercent.ToString("N0")}%");
    Console.WriteLine($"Your grade is ............. {test.Grade}");
    Console.WriteLine($"The total time was ........ {test.ElapsedSeconds.ToString("N2")} seconds");

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}