C# - Delays using Console

Electronics Computer Programming Q&A
Post Reply
User avatar
atferrari
Posts: 24
Joined: Sat Nov 22, 2008 11:02 pm
Location: Buenos Aires - Argentina
Contact:

C# - Delays using Console

Post by atferrari » Sun Jan 04, 2009 2:51 am

C# - Using Console.

I need to implement delays between actions.

They should happen once or be asigned to repetitive actions.

I identified Threading.Timer and Timers.Timer already but I can not find how they should be used.

Could anyone explain how, showing a sample of code?

Gracias.

User avatar
kheston
Posts: 348
Joined: Wed Dec 03, 2003 1:01 am
Location: CA
Contact:

Post by kheston » Sun Jan 04, 2009 7:24 am

Give this a try:

Code: Select all

using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        System.Timers.Timer timr;  // one of a few Timer objects available

        public Program()
        {
            timr = new System.Timers.Timer();
            timr.Elapsed += new ElapsedEventHandler(Timer_Tick); // register a handler
            timr.Interval = 1000; // raise Timer_Tick event once per second
            timr.Start();
        }

        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            Console.Write("\r{0}", DateTime.Now);
        }

        static void Main(string[] args)
        {
            new Program();
            Thread.Sleep(30 * 1000); // wait for 30 seconds before ending program
        }
    }
}
Kurt - SF Bay

User avatar
atferrari
Posts: 24
Joined: Sat Nov 22, 2008 11:02 pm
Location: Buenos Aires - Argentina
Contact:

Starting to grasp the concept.

Post by atferrari » Sun Jan 04, 2009 3:03 pm

Hola Kurt,

I just tested it and, of course, it works.

It is late now and I face a busy week ahead. As soon as I can I will revert with eventual more questions.

I need getting used to the structure of C# yet!

Gracias for replying and Happy New Year!

User avatar
atferrari
Posts: 24
Joined: Sat Nov 22, 2008 11:02 pm
Location: Buenos Aires - Argentina
Contact:

Few questions, Kurt

Post by atferrari » Fri Jan 09, 2009 1:27 pm

Hola Kurtz,

Thanks to your code (and with no background in any modern language), I learnt about subscriber and handler for events but there are few things I could not grasp yet:

a) Tried to change the name of the method public Program() but the compiler complains. Why should I keep the same name as the class? AFAIK a class can contain more than one method defined...

b) Why new Program(); is used inside Main? Am I not calling a method from the class? Or am I constructing something? I tried Program(); alone but the compiler didn't like it. At lost here :shock:

c) How could I do to have two or three handlers, for different timing and, of course, doing different things, as Timer_Tick?

Gracias for any help you could give again!

Code: Select all

{
    class Program
    {
        System.Timers.Timer timr;  // one of a few Timer objects available

        public Program()
        {
            timr = new System.Timers.Timer();
            timr.Elapsed += new ElapsedEventHandler(Timer_Tick); // register a handler
            timr.Interval = 1000; // raise Timer_Tick event once per second
            timr.Start();
        }

        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            Console.Write("\r{0}", DateTime.Now);
        }

        static void Main(string[] args)
        {
            new Program();
            Thread.Sleep(30 * 1000); // wait for 30 seconds before ending program
        }
    }
}

User avatar
atferrari
Posts: 24
Joined: Sat Nov 22, 2008 11:02 pm
Location: Buenos Aires - Argentina
Contact:

Question c) is solved

Post by atferrari » Sat Jan 10, 2009 1:39 am

Hola Kurtz,

Regarding my previous, question c) was solved but a) and b) still stand. :sad:

Could you help?

Gracias.

User avatar
kheston
Posts: 348
Joined: Wed Dec 03, 2003 1:01 am
Location: CA
Contact:

Post by kheston » Sat Jan 10, 2009 8:34 am

Program() is the "constructor" for the class. Notice it has the same name as the class itself, this is how a constructor is different from a method. It is essentially still a method, but it is only called when an object is created. Entire chapters in programming language books are devoted to what constructors do.

You can change the constructor, but the change can only be to the arguments it will have. For example: say I want to pass in the number of milliseconds, all I need to do is change the constructor's arguments to include an "int" argument that I can then use to initialize the class. A class can have multiple constructors, each must differ in the arguments one can pass in. This is called "constructor overloading."

The reason I'm calling the Program() method in the main method is: I'm essentially saying to the class, "give me back an instance (object) of yourself and build it with the constructor I'm calling." What's confusing about the way I wrote the code is I didn't assign the "new Program()" call to a variable. So, it looks a heck of a lot like a plain method rather than a constructor.

I've attached some more code that I hope will illustrate better some things you can do with constructors, methods, and the objects they operate on/within. See if you can figure out what I'm up to and feel free to post any questions you have.

By the way, by needing a timer you've jumped right into a program that involves threading. I've further thrown you to the wolves (though with the best of intentions) by posting a program below that creates multiple timers/threads/objects. The hope is that by monkeying with it a little you will solidify your understanding of classes and instances of those classes. However, you're now in deeper water than most noobs swim through at first. So, if it's too confusing, stick to one instance of this class with just the one timer (comment out the other instances within the main method). This way, there will only be 2 threads to manage (with the main thread doing very little) and no synchronization required. An understanding of thread synchronization comes later in your travels, I'm not attempting to do any here.

Code: Select all

using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        System.Timers.Timer timr;  // one of a few Timer objects available
        string name = "anonymous";
        int numTicks = 1;

        public Program()
        {
            // this is the default constructor.  No arguments are passed in
            timr = new System.Timers.Timer();
            timr.Elapsed += new ElapsedEventHandler(Timer_Tick); // register a handler
            timr.Interval = 1000; // raise Timer_Tick event once per second
            timr.Start();
        }

        public Program(int millis,string threadName)
        {
            timr = new System.Timers.Timer();
            timr.Elapsed += new ElapsedEventHandler(Timer_Tick); // register a handler
            timr.Interval = millis;
            name = threadName;
            timr.Start();
        }

        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            // here I added the name variable to identify the object uniquely
            Console.Write(name + " {0}: {1}\n", numTicks, DateTime.Now);
            numTicks++;
        }

        public void changeTickWaitTime(int millis)
        {
            // this demonstrates operating on a given instance of the class
            timr.Interval = millis;
            Console.Write("\n" +name + ": Interval time is now: {0}\n\n", millis);
        }

        static void Main(string[] args)
        {
            /* 
             * This method's presence within the class itself is a bit confusing.  Think of it as
             * though it was not here but was actually outside the class definition.  The main
             * method is creating and calling the class' objects, the class does not create or run
             * the main method as it's placement in the code would seem to infer.
             * 
             * instance1, instance2, and instance3 are separate instances (objects) of the "Program"
             * class.  Though each of them is writing to the same console, think of each as a
             * separate being (or life in memory).
            */
            Console.Write("\nCreating the instance without a name.\n\n");
            Program instance1 = new Program(); // create an object
            Thread.Sleep(5 * 1000);
            
            Console.Write("\nCreating the speedy instance.\n\n");
            Program instance2 = new Program(500, "speedy"); // create an object with the other constructor
            Thread.Sleep(5 * 1000);

            Console.Write("\nCreating the slug instance.\n\n");
            Program instance3 = new Program(3000, "slug"); // create an object with the other constructor
            Thread.Sleep(15 * 1000);
            
            instance1.changeTickWaitTime(1500);
            // now there will be ~3 speedy ticks per anonymous tick
            instance3.changeTickWaitTime(2000); // make slug less sluggish
            // now there will be ~4 speedy ticks per slug tick
            
            Thread.Sleep(60 * 1000); // wait for 30 seconds before ending program
        }
    }
}
Kurt - SF Bay

User avatar
atferrari
Posts: 24
Joined: Sat Nov 22, 2008 11:02 pm
Location: Buenos Aires - Argentina
Contact:

Started to grasp it!

Post by atferrari » Mon Jan 12, 2009 3:04 pm

Hola Kurtz,

Definitely now I understand: I need to instantiate the class before anything. As it is, the class is just a model ("blueprint", says Microsoft).

In my mind I was trying to instantiate a method (?!) :sad: but rereading yours all started to make sense.

I am not playing the macho man but the timers stuff seems reasonably easy to understand (well, running through your code I can see what and how you did it). I do not dance with wolves but they are friendly with me for the moment! :grin:

BTW: I discovered the beauty of try and catch. After working in Assembler for PIC micros I can appreciate how nice it is!

Gracias for the help!

Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests