计时器设计

 这里说的计时器是类似于秒表的东西,可以在一旁显示计时,是编写某些游戏必不可少的部分。下面通过一个例子来介绍如何添加:

//Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;                        //需要用到线程

namespace Timer
{
    class Program
    {
        static void Main(string[] args)
        {
            StopWatch sw = new StopWatch();
            sw.Start();
        }
    }

    class StopWatch
    {
        private int Interval = 1000;              //时间间隔,单位毫秒
        private int Time = 0;                        //所显示的时间

        public void Start()
        {
            Thread timer = new Thread(new ThreadStart(Timer));  //新建一个线程,该线程调用Timer()
            timer.Start();                               //启动线程
            Console.CursorVisible = false;   //隐藏光标
            Console.ReadKey(true);            //等待按任意键退出
            timer.Abort();                              //终止线程,用于停止秒表
        }

        private void Timer()
        {
            while (true)
            {
                Display();                               //显示秒表计数
                Thread.Sleep(Interval);         //等待1秒后再执行Timer()刷新计数
                Time++;                                 //秒数加1
            }
        }

        private void Display()
        {
            Console.SetCursorPosition(0, 0);
            Console.Write("Time:" + Time.ToString());
        }
    }
}

       想必看完程序大家对其中的方法已经很了解了,就不再赘述。程序可直接拷过去运行,运行结果是一个在控制台左上角显示的秒表,按任意键退出。

       这个程序中可扩展的部分为Display(),可以换成执行其他操作的函数。它可以间歇地执行,以实现某种特定的功能,而它等待的时间即是由Interval决定的。

 

转自:http://gaofeihang.blog.163.com/blog/static/8450828520086524419527/

转载于:https://www.cnblogs.com/Sue_/articles/1654312.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值