Free mag vol1 | Page 783

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING class Program { static void PrintTime(object state) { Console.WriteLine("Time is: {0}", DateTime.Now.ToLongTimeString()); } static void Main(string[] args) { } } Notice the PrintTime() method has a single parameter of type System.Object and returns void. This is not optional, given that the TimerCallback delegate can only call methods that match this signature. The value passed into the target of your TimerCallback delegate can be any type of object (in the case of the e-mail example, this parameter might represent the name of the Microsoft Exchange server to interact with during the process). Also note that given that this parameter is indeed a System.Object, you are able to pass in multiple arguments using a System.Array or custom class/structure. The next step is to configure an instance of the TimerCallback delegate and pass it into the Timer object. In addition to configuring a TimerCallback delegate, the Timer constructor allows you to specify the optional parameter information to pass into the delegate target (defined as a System.Object), the interval to poll the method, and the amount of time to wait (in milliseconds) before making the first call. For example: static void Main(string[] args) { Console.WriteLine("***** Working with Timer type *****\n"); // Create the delegate for the Timer type. TimerCallback timeCB = new TimerCallback(PrintTime); // Establish timer settings. Timer t = new Timer( timeCB, // The TimerCallback delegate object. null, // Any info to pass into the called method (null for no info). 0, // Amount of time to wait before starting (in milliseconds). 1000); // Interval of time between calls (in milliseconds). } Console.WriteLine("Hit key to terminate..."); Console.ReadLine(); In this case, the PrintTime() method will be called roughly every second and will pass in no additional information to said method. Here is the output: ***** Working with Timer type ***** Hit key to terminate... Time is: 6:51:48 PM Time is: 6:51:49 PM Time is: 6:51:50 PM 728