Why the following program only output a single line of "World"? I expect it to output "Hello" every second and finally "World"
Also, how to control the how long the timer will work? Or, in this program, how to control the number of "Hello"s it outputs?
Thanks
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
public int count = 0;
static void Main(string[] args)
{
//TimerCallback command = new TimerCallback(SendCommand);
Timer t = new Timer(SendCommand, null, 0, 1000);
Console.WriteLine("World");
}
public static void SendCommand(object s)
{
Console.WriteLine("Hello");
}
}
}
usfishPosted Nov 20, 2007, 8:59 PM
Jan MontanoPosted Nov 19, 2007, 9:06 PM
Hi Usfish,
Try putting a Console.Readline() at the end of your Main method. You'll see that it will only output 1 "World" and output "Hello" every second. The line Timer t = new Timer(SendCommand, null, 0, 1000) is not a blocking call meaning it will not wait on that line and finish the processing before proceeding to the next line which is Console.WriteLine("World")
I am not sure if there's a built-in property to set how long the timer will work. But if you need to control the number of "Hello"s, one option is having a static variable for count (though this may not be the best solution).
class
Program{
public static int count = 0; public static int max = 5; static void Main(string[] args){
Timer t = new Timer(SendCommand, null, 0, 1000); Console.WriteLine("World"); Console.ReadLine();}
public static void SendCommand(object s){
if (count < max){
Console.WriteLine("Hello");count++;
}
}
}
Cheers,
Jan