Tải bản đầy đủ - 0 (trang)
4-3. Execute a Method Periodically

4-3. Execute a Method Periodically

Tải bản đầy đủ - 0trang

CHAPTER 4 ■ THREADS, PROCESSES, AND SYNCHRONIZATION



Solution

Declare a method containing the code you want to execute periodically. The method’s signature

must match that defined by the System.Threading.TimerCallback delegate; in other words, it must

return void and take a single object argument. Create a System.Threading.Timer object and pass it the

method you want to execute along with a state object that the timer will pass to your method when the

timer expires. The runtime will wait until the timer expires and then call your method using a thread

from the thread pool.



■ Tip If you are implementing a timer in a Windows Forms application, you should consider using the

System.Windows.Forms.Timer, which also provides additional support in Visual Studio that allows you to drag the

timer from your toolbox onto your application. For server-based applications where you want to signal multiple

listeners each time the timer fires, consider using the System.Timers.Timer class, which notifies listeners using

events.



How It Works

It is often useful to execute a method at regular intervals. For example, you might need to clean a data

cache every 20 minutes. The Timer class makes the periodic execution of methods straightforward,

allowing you to execute a method referenced by a TimerCallback delegate at specified intervals. The

referenced method executes in the context of a thread from the thread pool. (See recipe 4-1 for notes on

the appropriate use of thread-pool threads.)

When you create a Timer object, you specify two time intervals. The first value specifies the

millisecond delay until the Timer first executes your method. Specify 0 to execute the method

immediately, and specify System.Threading.Timeout.Infinite to create the Timer in an unstarted state.

The second value specifies the interval in milliseconds; then the Timer will repeatedly call your method

following the initial execution. If you specify a value of 0 or Timeout.Infinite, the Timer will execute the

method only once (as long as the initial delay is not Timeout.Infinite). You can specify the time

intervals as int, long, uint, or System.TimeSpan values.

Once you have created a Timer object, you can modify the intervals used by the timer using the

Change method, but you cannot change the method that is called. When you have finished with a Timer

object, you should call its Dispose method to free system resources held by the timer. Disposing of the

Timer object cancels any method that is scheduled for execution.



The Code

The TimerExample class shown next demonstrates how to use a Timer object to call a method named

TimerHandler. Initially, the Timer object is configured to call TimerHandler after 2 seconds and then at 1second intervals. The example allows you to enter a new millisecond interval in the console, which is

applied using the Timer.Change method.



164



www.it-ebooks.info



CHAPTER 4 ■ THREADS, PROCESSES, AND SYNCHRONIZATION



using System;

using System.Threading;

namespace Apress.VisualCSharpRecipes.Chapter04

{

class Recipe04_03

{

public static void Main()

{

// Create the state object that is passed to the TimerHandler

// method when it is triggered. In this case, a message to display.

string state = "Timer expired.";

Console.WriteLine("{0} : Creating Timer.",

DateTime.Now.ToString("HH:mm:ss.ffff"));

// Create a timer that fires first after 2 seconds and then every

// second. Use an anonymous method for the timer expiry handler.

using (Timer timer =

new Timer(delegate(object s)

{Console.WriteLine("{0} : {1}",

DateTime.Now.ToString("HH:mm:ss.ffff"),s);

}

, state, 2000, 1000))

{

int period;

// Read the new timer interval from the console until the

// user enters 0 (zero). Invalid values use a default value

// of 0, which will stop the example.

do

{

try

{

period = Int32.Parse(Console.ReadLine());

}

catch (FormatException)

{

period = 0;

}

// Change the timer to fire using the new interval starting

// immediately.

if (period > 0) timer.Change(0, period);

} while (period > 0);

}



165



www.it-ebooks.info



CHAPTER 4 ■ THREADS, PROCESSES, AND SYNCHRONIZATION



// Wait to continue.

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



4-4. Execute a Method at a Specific Time

Problem

You need to execute a method in a separate thread at a specific time.



Solution

Declare a method containing the code you want to execute. The method’s signature must match that

defined by the System.Threading.TimerCallback delegate; that is, it must return void and take a single

object argument. Create a System.Threading.Timer object, and pass it the method you want to execute

along with a state object that the timer will pass to your method when the timer expires. Calculate the

time difference between the current time and the desired execution time, and configure the Timer object

to fire once after this period of time.



How It Works

Executing a method at a particular time is often useful. For example, you might need to back up data at 1

a.m. daily. Although primarily used for calling methods at regular intervals, the Timer object also

provides the flexibility to call a method at a specific time.

When you create a Timer object, you specify two time intervals. The first value specifies the

millisecond delay until the Timer first executes your method. To execute the method at a specific time,

you should set this value to the difference between the current time (System.DateTime.Now) and the

desired execution time. The second value specifies the interval after which the Timer will repeatedly call

your method following the initial execution. If you specify a value of 0,

System.Threading.Timeout.Infinite, or TimeSpan(-1), the Timer object will execute the method only

once. If you need the method to execute at a specific time every day, you can easily set this figure using

TimeSpan.FromDays(1), which represents the number of milliseconds in 24 hours.



The Code

The following code demonstrates how to use a Timer object to execute a method at a specified time:

using System;

using System.Threading;

using System.Globalization;



166



www.it-ebooks.info



CHAPTER 4 ■ THREADS, PROCESSES, AND SYNCHRONIZATION



namespace Apress.VisualCSharpRecipes.Chapter04

{

class Recipe04_04

{

public static void Main(string[] args)

{

// Create a 30-second timespan.

TimeSpan waitTime = new TimeSpan(0, 0, 30);

// Create a Timer that fires once at the specified time. Specify

// an interval of -1 to stop the timer executing the method

// repeatedly. Use an anonymouse method for the timer expiry handler.

new Timer(delegate(object s)

{

Console.WriteLine("Timer fired at {0}",

DateTime.Now.ToString("HH:mm:ss.ffff"));

}

, null, waitTime, new TimeSpan(-1));

Console.WriteLine("Waiting for timer. Press Enter to terminate.");

Console.ReadLine();

}

}

}



4-5. Execute a Method by Signaling a WaitHandle Object

Problem

You need to execute one or more methods automatically when an object derived from

System.Threading.WaitHandle is signaled.



Solution

Declare a method containing the code you want to execute. The method’s signature must match that

defined by the System.Threading.WaitOrTimerCallback delegate. Using the static

ThreadPool.RegisterWaitForSingleObject method, register the method to execute and the WaitHandle

object that will trigger execution when signaled.



How It Works

You can use classes derived from the WaitHandle class to trigger the execution of a method. Using the

RegisterWaitForSingleObject method of the ThreadPool class, you can register a WaitOrTimerCallback

delegate instance for execution by a thread-pool thread when a specified WaitHandle-derived object

enters a signaled state. You can configure the thread pool to execute the method only once or to

automatically reregister the method for execution each time the WaitHandle is signaled. If the WaitHandle



167



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

4-3. Execute a Method Periodically

Tải bản đầy đủ ngay(0 tr)

×