繁体   English   中英

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

[英]C# Timer (Console Application)

我正在尝试为服务器测试员工的程序,在程序中我需要一个计时器来知道他们回答所有问题花了多长时间,程序快要完成了,我唯一需要的就是计时器,我需要计时器从0开始计数,并在变量“ TestFinished”为true时停止。 我发现了这个计时器,即时通讯试图从“ 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

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;

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

您应该使用Stopwatch来测量时间。 那就是它的目的。 只需在要测量的操作之前调用Start()然后在完成后立即调用Stop() 然后,您可以按照“ Ticks ,“ Milliseconds ”或“时间TimeSpan来访问经过的时间。

例如,假设您调用了某种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();
    }
}

为了完整QuizItemQuizItem只是一个简单的类,您可以填充一个问题,一个或多个可能的答案以及正确答案的索引。 然后,它知道如何提出问题,获取响应并返回true或false:

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();
}

输出量

在此处输入图片说明

暂无
暂无

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

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