views:

106

answers:

3

I would like to attach an event handler to a Stop Watch. Can someone please provide a code snippet in C# or VB?

I'v Bing'd it with no luck.

+4  A: 

Have a Bing for Timer instead... That ought get you there... One decent one in particular: http://dotnetperls.com/timer

Reddog
@Bram: Also be aware that there are a few different Timer implementations (e.g. System.Threading.Timer and System.Timers.Timer and System.Windows.Forms.Timer). Choose wisely...
Reddog
A: 

Stopwatch doesn't have any events to subscribe to. Maybe if you clarified what you were actually trying to do someone can help.

John Rasch
Every time the StopWatch ticks, raise another sub.
Bram
@Bram - I think you really want a `Timer` as Reddog suggests, the `Stopwatch` in .NET is used for high-precision timing... the event would be firing essentially every nanosecond.
John Rasch
Yep, sorry, a timer is what I was after. Found a sample here http://pagebrooks.com/archive/2008/03/07/silverlight-2-has-a-timer-dispatchertimer.aspx. Thanks for the help.
Bram
A: 

here is an example of a Timer I use for a backup program I wrote that will start in 5 seconds after instantiating it and fire the callback (tick) every hour:

    private System.Threading.Timer AutoRunTimer; 

    private void Form1_Load(object sender, EventArgs e)
    {
        mybackups = new BackupService();
        AutoRunTimer = new System.Threading.Timer(tick, "", new TimeSpan(0, 0, 5), new TimeSpan(1, 0, 0));     
    }

    private void tick(object data)
    {
        if (DateTime.Now.Hour == 1 && DateTime.Now.Subtract(lastRun).Hours >= 1) // run backups at first opportunity after 1 am
        {
            startBackup("automatically");
        }
    }
senloe