RSS

Monthly Archives: August 2012

A Simple Defibrillator Class in C#

Timeout Defibrillators are common in the ASP.NET world, where there is often a requirement to keep a session alive during a period of inactivity.  However the same can be said about the windows application domain.  For example, assume that user enters an area of the application which serves up some specific data.  While the user has this screen open, it should be locked to all other users so that the data cannot be modified.  But what happens if the user decides to go to lunch with the screen open preventing all other users from working.

In scenarios like this it would be nice to have a simple class which when invoked starts a timeout process for long periods of inactivity.  When this time out is reached an event is raised to the calling object which allows the application to release the lock.  Additionally there is a method in the class which can be called by the parent object to reset the timer if there is some form of activity on the screen.

Below is my simple Defibrillator class and below that an explanation of the key points of this class and how to use it.

Defibrillator Class

So the basics of this class are:

  • A delegate and event have been created at the top of this page which can be subscribed to by the calling object.  This allows us to raise an event to the parent once the time out has been reached.
  • The constructor allows the user to pass in the time is seconds which should be observed before the timeout is reached.
  • The Start method is called when we are ready to commence the timer.  Note that I have set the Interval between ticks to be 1 second.  The timer object allows us to set a call back method which is invoked after every tick (1 second interval in this case)
  • The Reset method allows us to Reset the timer.  This would probably be called if the parent registers user activity.
  • The TimerProc method is called after every tick of the timer.  Here I am performing a check to see if the timeout has been reached.  If it has the timer is disposed and the event raised back to the Parent.

 

To use the class, simply create a Form which has a reference to the Defibrillator class and add code similar to below:

Invoking the class

Here I am creating an instance of the class with a 10 second timeout.  I am also subscribing to the TimeOut Reached event which will call the method dt_TimeOutReached when the time out completes.

All that’s left is to start the Timer – dt.Start()

 

Advertisements