Timing a process
So I wanted to see how long some of my code took and if it didn’t take long enough, make it take longer. Yes, I really said that and I have a good reason for it.
My use case is this:
- I have a process that is being kicked off using BackgroundWorker.
- For user experience reasons, I wanted my WPF GUI spinner to have a minimum time of 1.2 seconds that it spins while a process runs.
See my spinner post: WPF replacement options for an animated gif or How to make a spinner?
Here is what I did:
void worker_DoWork(object sender, DoWorkEventArgs e) { Stopwatch timer = new Stopwatch(); timer.Start(); // Now lets do the work that you need a spinner for // Your code goes here .... timer.Stop(); // Lets make sure the GUI spinner has at least 1.2 seconds of spin int i = 1200 - (int)timer.ElapsedMilliseconds; if (i > 0) Thread.Sleep(i); }