Click here to Skip to main content
15,887,379 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have made a timer which runs backwards starting from 10.I just wanna create a little simple game.I wanna write the sentence 'I love programming' under 10 seconds if i am able to do it the message should shown 'You win , gratz' but when the clock runs out of time the message should be shown 'you lose' but its not picking up the sentence and when I write,it disappears.I tried doing it here is my code.

What I have tried:

C#
class Program
   {
       static Timer timer = new Timer(1000);
       static int i = 10;

       static void Main(string[] args)
       {
           Console.WriteLine("Write the sentence in 10 seconds");
           Console.WriteLine("I love programming");
           Console.ReadKey();
           timer.Elapsed += timer_Elapsed;
           timer.Start();
           Console.Read();
       }

       private static void timer_Elapsed(object sender, ElapsedEventArgs e)
       {
           i--;
           Console.Clear();
           Console.WriteLine("=======================");
           Console.WriteLine("  Time is running out       ");
           Console.WriteLine("");
           Console.WriteLine("The Clock starts: {0}", i.ToString());
           Console.WriteLine("");
           Console.WriteLine("=======================");

           while (true)
           {
               if (Console.ReadLine() == "I love programming")
               {
                   Console.Clear();
                   Console.WriteLine("=======================");
                   Console.WriteLine("     You Win                     ");
                   Console.WriteLine("");
                   Console.WriteLine("     Gratz                      ");
                   Console.WriteLine("");
                   Console.WriteLine("=======================");
                   timer.Stop();
                   timer.Dispose();

               }
           }

           GC.Collect();
       }
   }
Posted
Updated 4-Feb-18 23:10pm

The problem is that the timer Elapsed event is raised on the thread that started it - the same thread that calls Console.Read.
Unfortunately, Console.Read is a blocking call - it doesn't return until the user input is complete, and that means the user pressing ENTER.

What you need to do is move the Timer onto a different thread so that it can operate independently of your main code. But ... that won't work for you either because your Elapsed code is also trying to read input from the user and ReadLine is also a blocking call. So it won't continue until the user types ENTER either! And you are looping forever inside the Elapsed method, so that will never end! But to make matters worse, you then have two competing threads trying to read from the same input, so what which one is going to get what is anybody's guess!

What you are trying to do is surprisingly complex: you will need to stop using blocking calls completely: which means you have to start thinking very, very differently.
This can be done as a console app: How to read what user wrote (without hitting enter) - console C# - Stack Overflow[^] but it's pretty advanced stuff. I'd strongly suggest that you leave this for a week or two when you get to Windows applications instead of Console ones which are much, much more suitable for multithreaded work, timers, and non-blocking inputs!
 
Share this answer
 
Comments
abdul wadood 5-Feb-18 8:15am    
Thank you for the info.Yes, you are right its pretty complex since i am a newbie I just wanted to test timer in console which i had done already in win form but thanks anyway.But can you advice on which projects individual must work on a Console app for beginners that will be useful for me to know.
OriginalGriff 5-Feb-18 8:32am    
It's not really a case of "you want to work on this type of project", so much as "console apps are for learning how to code in .NET" - at least until you get good experience, and then you know when to use them. Most of the time these days a windows (or web) app is a better choice as users are a lot more familiar with them and how to use them.

I wouldn't put a lot of work into doing complicated stuff in a console app - the input and out restrictions make it complicated as Carlo's answer shows. It's not at all obvious what is happening there, or why, and that make s it difficult to write code you can work on later.

A similar app in WinForms is much easier to write, because they are already based around the concept of events and event driven programming - unlike console apps which are pretty much always procedural and have difficulty working with events as a result. I'd go back to your course book and try some of the exercises - they will teach you a lot more (and in a better structured way) than randomly trying to get an app running! :laugh:
abdul wadood 5-Feb-18 9:10am    
I thought every beginner learning C# starts from Console applications to learn some basics thats why i started it...I will learn basics from here and then switched on to Winform soon
OriginalGriff 5-Feb-18 10:02am    
That sounds a lot like "I'm doing this on my own" - if so, stop right now!
Instead, get a book - or better a course - and follow that from start to finish. The material will be introduced in a structured way with exercises to make sure you understand what you are doing at each stage before building on that for the next stage. (Addison Wesley do good ones, as do Wrox and Microsoft Press)
Trying to pick it up as you go along won't get you far because you will have no idea what you don't know that could have made your life a whole load easier!
abdul wadood 5-Feb-18 11:41am    
Sounds great! I will look for the books and the courses.Thank you very much :D
is there anyway in this website where I can contact you if i needed some help - just saying I am eager to learn programming I know i will be needing a lot more advice in the future :laugh:
You have to asynchronously read characters form the console, add them up to a string and report such a string on timer handler. A quick and dirty solutions could be something like
C#
class Program
{
    static Timer timer = new Timer(1000);
    static int i = 10;
    static string sin;

    static void Main(string[] args)
    {
        sin = string.Empty;
        Console.WriteLine("Write the sentence in 10 seconds");
        Console.WriteLine("I love programming");
        timer.Elapsed += timer_Elapsed;
        timer.Start();
        while (i != 0)
        {
            if (Console.KeyAvailable)
            {
                sin += Console.ReadKey(true).KeyChar;
            }
        }
        timer.Stop();
        if (sin == "I love programming")
            Console.WriteLine("OK");
        else
            Console.WriteLine("KO");
    }

    private static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        i--;
        Console.Clear();
        Console.WriteLine("=======================");
        Console.WriteLine("  Time is running out       ");
        Console.WriteLine("");
        Console.WriteLine("The Clock starts: {0}", i.ToString());
        Console.WriteLine("");
        Console.WriteLine(sin);
        Console.WriteLine("=======================");
    }
}
 
Share this answer
 
Comments
abdul wadood 5-Feb-18 8:17am    
Yes it works now.But need to understand what you did there step by step cause i just copied the code from here still feeling confused tho.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900