Chapter110:Timers

No Comments

Section110.1:MultithreadedTimers
System.Threading.Timer-Simplestmultithreadedtimer.Containstwomethodsandoneconstructor.

Example: A timer calls the DataWrite method, which writes “multithread executed…” after five seconds have elapsed, and then every second after that until the user presses Enter:

usingSystem;

usingSystem.Threading;

classProgram

{

staticvoidMain()

{

//Firstinterval=5000ms;subsequentintervals=1000ms

Timertimer=newTimer(DataWrite,”multithreadexecuted…”,5000,1000); Console.ReadLine();

timer.Dispose();//Thisbothstopsthetimerandcleansup.

}

staticvoidDataWrite(objectdata)

{

//Thisrunsonapooledthread

Console.WriteLine(data);//Writes”multithreadexecuted…”

}

}

Note:Willpostaseparatesectionfordisposingmultithreadedtimers.

Change-Thismethodcanbecalledwhenyouwouldlikechangethetimerinterval.

Timeout.Infinite- If youwant to firejust once. Specifythis in thelast argument of theconstructor.

System.Timers-Anothertimerclassprovidedby.NETFramework.ItwrapstheSystem.Threading.Timer.

Features:

  • IComponent- Allowing it to be sited in the Visual Studio’sDesigner’scomponent tray
  • Intervalproperty instead of a Changemethod
  • Elapsedeventinstead of a callback delegate
  • Enabledpropertytostartandstopthetimer(defaultvalue=false)
  • Start&StopmethodsincaseifyougetconfusedbyEnabledproperty(abovepoint)
  • AutoReset- for indicating a recurring event (defaultvalue=true)
  • SynchronizingObjectproperty with Invokeand BeginInvokemethods for safely calling methods on WPF elementsandWindowsFormscontrols

Examplerepresentingalltheabovefeatures:

usingSystem;

usingSystem.Timers;//TimersnamespaceratherthanThreading

classSystemTimer

{

staticvoidMain()

{

Timertimer=newTimer();//Doesn’trequireanyargs

timer.Interval=500;

timer.Elapsed+=timer_Elapsed;//Usesaneventinsteadofadelegate

timer.Start();//Startthetimer

Console.ReadLine();timer.Stop();//S

topthetimer Console.ReadLine();

timer.Start();//Restartthetimer

Console.ReadLine();

timer.Dispose();//Permanentlystopthetimer

}

staticvoidtimer_Elapsed(objectsender,EventArgse)

{

Console.WriteLine(“Tick”);

}

}

Multithreadedtimers-usethethreadpooltoallowafewthreadstoservemanytimers.Itmeansthatcallback methodorElapsedeventmaytriggeronadifferentthreadeachtimeitiscalled.
Elapsed-thiseventalwaysfiresontime—regardlessofwhetherthepreviousElapsedeventfinishedexecuting. Becauseofthis,callbacksoreventhandlersmustbethread-safe.Theaccuracyofmultithreadedtimersdependson the OS, and is typically in the 10–20 ms.
interop-wheneveryouneedgreateraccuracyusethisandcalltheWindowsmultimediatimer.Thishasaccuracy down to 1 ms and it is defined in winmm.dll.

timeBeginPeriod-CallthisfirsttoinformOSthatyouneedhightimingaccuracy timeSetEvent- call this after timeBeginPeriodto start a multimedia timer. timeKillEvent- call this when you are done, this stops the timer
timeEndPeriod-CallthistoinformtheOSthatyounolongerneedhightimingaccuracy.

YoucanfindcompleteexamplesontheInternetthatusethemultimediatimerbysearchingforthekeywords
dllimportwinmm.dlltimesetevent.

Section110.2:CreatinganInstanceofaTimer
Timersareusedtoperformtasksatspecificintervalsoftime(DoXeveryYseconds)Belowisanexampleof creating a new instance of a Timer.
NOTE:ThisappliestoTimersusingWinForms.IfusingWPF,youmaywanttolookintoDispatcherTimer

usingSystem.Windows.Forms;//TimersusetheWindows.Formsnamespace

publicpartialclassForm1:Form

{

TimermyTimer=newTimer();//createaninstanceofTimernamedmyTimer

publicForm1()

{

InitializeComponent();

}

}

Section110.3:Assigningthe”Tick”eventhandlertoaTimer
Allactionsperformedinatimerarehandledinthe”Tick”event.

publicpartialclassForm1:Form

{

TimermyTimer=newTimer();

publicForm1()

{

InitializeComponent();

myTimer.Tick+=myTimer_Tick;//assigntheeventhandlernamed”myTimer_Tick”

}

privatevoidmyTimer_Tick(objectsender,EventArgse)

{

//Performyouractionshere.

}

}

Section110.4:Example:UsingaTimertoperformasimple countdown

publicpartialclassForm1:Form

{

TimermyTimer=newTimer();

inttimeLeft=10;

publicForm1()

{

InitializeComponent();

//setpropertiesfortheTimer

myTimer.Interval=1000;

myTimer.Enabled=true;

//Settheeventhandlerforthetimer,named”myTimer_Tick”

myTimer.Tick+=myTimer_Tick;

//Startthetimerassoonastheformisloaded

myTimer.Start();

//Showthetimesetinthe”timeLeft”variable

lblCountDown.Text=timeLeft.ToString();

}

privatevoidmyTimer_Tick(objectsender,EventArgse)

{

//performtheseactionsattheintervalsetintheproperties.

lblCountDown.Text=timeLeft.ToString();

timeLeft-=1;

if(timeLeft<0)

{

myTimer.Stop();

}

}

}

Resultsin…

Andsoon…

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment