September 8, 2024

Using Thread.Sleep() -- and some class tricks

We are adding quite a bit here. The main idea is to play with the call to Thread.Sleep(). In short, everything runs as a thread, and you can tell the system you would like some "time out" in the form of a delay. You specify the size of the delay in milliseconds, so 1000 of them gives you a full second. Using this the specified number of messages comes out, once per second.
using System;
using System.Threading.Tasks;

namespace Example
{
    public class Wally
    {
        private static int delay = 10;

        public static int Delay {
            get { return delay; }
            set { delay = value; }
        }

        public static void chat ( string msg, int repeat )
        {
            for ( int i=0; i<repeat; i++ ) {
                Console.WriteLine ( msg );
                Thread.Sleep ( delay );
            }
        }
    }
}

namespace HogHeaven
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Example.Wally.Delay = 1000;
            Example.Wally.chat ( "Kilroy is here !!", 4 );
            Console.WriteLine ( "All done" );
        }
    }
}
// THE END
A brief note here. I added the "using System.Threading.Tasks;" statment at the top that should be required to give access to Thread.Sleep(). But the code compiled without it, so either the compiler is being clever and covering my omissions or I am generally confused.

"Why do I put "THE END" at the end of every file?" - I hear you asking.
Well, I have been tricked before by my editor about the end of the screen being the end of the file. This eliminates that ambiguity, but suit yourself.

An interesting business here is the get and set for the private delay variable. What is going on should sort of be obvious. You can write to or read from the "Delay" pseudo variable to write or read the private "delay" variable. An entirely different naming scheme could have been chosen.

A quick aside (and something for me to tackle down the road). The whole Thread.Sleep() business is ripe for being handled in another way using Thread.Delay() along with async and await(). Stay tuned for that.

And let's talk about some OO jargon. A class consists of fields and methods -- at least I think that is what they want to call them in C#. A method is what we would call a function in C -- it is a lump of callable executable code, all packaged up nicely. A field is some data item or "variable" that is part of the class. Now when we declare something like "Delay" with what look like get and set methods (that never acutally get called) we are declaring a Property. C# has some fancy shorthand for dealing with properties. We will look at some of that in the next section.


Feedback? Questions? Drop me a line!

Tom's Computer Info / tom@mmto.org