简体   繁体   中英

A timer with c# console

I'm using c# console . I have a timer like : int TimeElasped = 0 to show and update times . it can resolve with a for( ; ; )

but computer cant do other codes !!! so I am using this code :

using System.Threading;


public class Test
{
    static int TimeElasped = 0;
    static void Main(string[] args)
    {

       Timer tm = new Timer(tm_tick,null,TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(1));
       Console.Write("");
       Console.ReadKey();
    }
    static void tm_tick(object obj)
    {
        Console.Clear();
        Console.WriteLine("Timer:{0}", TimeElasped );
        Counter++;
    }
}

I Cannot use Console.Clear() because it clear all data in console , when I remove Console.Clear() timer is showing line by line !!!

so how can I have a timer that update time ?

thanks ,

If you want to display the time as it ticks in a console, you will need to clear the window and "redraw" everything with the updated time:

static void tm_tick(object obj)
    {   
        Console.Clear();
        Console.WriteLine("===========================================================================");
        Console.WriteLine("Bunch of stuff here to look pretty");        
        Console.WriteLine("===========================================================================");
        Console.WriteLine("");        
        Console.WriteLine("Timer:{0}", TimeElasped );
        Counter++;
    }

However this is based on your initial question, where I can only presume that you are trying to have just the time change and nothing else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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