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

时间:2017-07-22 20:20:22

标签: c#

我正在尝试为测试其员工的服务器创建一个程序,在程序中我需要一个计时器来知道他们花了多长时间来回答所有问题,程序几乎完成,我唯一需要的东西是一个计时器,我需要计时器从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++;
    }
}

3 个答案:

答案 0 :(得分:2)

简单的方法是使它成为一个领域。

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

答案 1 :(得分:0)

1)要使代码编译,你必须在类范围中声明静态变量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)您可以使用StopWatch来衡量已用时间:

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

答案 2 :(得分:0)

Timer不是很精确,不应该用于衡量时间,而应该用于安排定期执行的代码。

您应该使用Stopwatch来衡量时间。这就是为它做的。只需在您要衡量的操作之前调用Start(),然后在Stop()完成后立即调用Ticks。然后,您可以使用MillisecondsTimeSpanTest来访问已用时间。

例如,假设您有一些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

为了完整起见,上面引用的class QuizItem { public string Question; public int IndexOfCorrectAnswer; public List<string> PossibleAnswers; private bool isMultipleChoice => PossibleAnswers.Count() > 1; public QuizItem(string question, List<string> possibleAnswers, int indexOfCorrectAnswer) { // Argument validation if (string.IsNullOrWhiteSpace(question)) throw new ArgumentException( "The question cannot be null or whitespace.", nameof(question)); if (possibleAnswers == null || !possibleAnswers.Any()) throw new ArgumentException( "The list of possible answers must contain at least one answer.", nameof(possibleAnswers)); if (indexOfCorrectAnswer < 0 || indexOfCorrectAnswer >= possibleAnswers.Count) throw new ArgumentException( "The index specified must exist in the list of possible answers.", nameof(indexOfCorrectAnswer)); Question = question; PossibleAnswers = possibleAnswers; IndexOfCorrectAnswer = indexOfCorrectAnswer; } public bool AskQuestion() { var correct = false; Console.WriteLine(Question); if (isMultipleChoice) { for (int i = 0; i < PossibleAnswers.Count; i++) { Console.WriteLine($" {i + 1}: {PossibleAnswers[i]}"); } int response; do { Console.Write($"\nEnter answer (1 - {PossibleAnswers.Count}): "); } while (!int.TryParse(Console.ReadLine().Trim('.', ' '), out response) || response < 1 || response > PossibleAnswers.Count); correct = response - 1 == IndexOfCorrectAnswer; } else { Console.WriteLine("\nEnter your answer below:"); var response = Console.ReadLine(); correct = IsCorrect(response); } Console.ForegroundColor = correct ? ConsoleColor.Green : ConsoleColor.Red; Console.WriteLine(correct ? "Correct" : "Incorrect"); Console.ResetColor(); return correct; } public bool IsCorrect(string answer) { return answer != null && answer.Equals(PossibleAnswers[IndexOfCorrectAnswer], StringComparison.OrdinalIgnoreCase); } } 只是一个简单的类,您可以填充问题,一个或多个可能的答案以及正确答案的索引。然后它知道如何提出问题,得到答案,并返回真或假:

QuizItem

使用这些类,它可以很容易地管理测试。您唯一要做的就是创建一些test.BeginTest();个对象,然后调用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(); } 。剩下的工作已经完成,包括获得经过的时间。

例如:

var scrollPos = $(window).scrollTop(),
    posY = Math.floor(0.2 * scrollPos);

$('.background-layer').css('background-position', '50% calc(50% + ' + posY + 'px)');

<强>输出

enter image description here