0

I'll be short and to the point. I basically need a way I can take a timer, check when the timer is up and execute something at the end of it, then loop it. For example (this code isn't serious, just example code) :

Timer1.start();

If (timer1.TimeRanOut) {

Timer2.start()

}

Or some other way to pause the timer without the GUI freezing up (I'll be running some things at a fast pace and freezing would get in the way). I'll be making this more complex by looping the entire process, like :

if (Checkbox1.checked == true; )
{
Timer1.start();

Next If (timer1.TimeRanOut) {

Timer2.start()

}

Next If (timer2.TimeRanOut) {

Timer3.start()

}

And so on. Any solutions?

2 Answers2

0

I would suggset working with Tasks. you set up a task to do something (it can just wait for X seconds, than it is a timer) than you set continueWith to assign a new task to run when the first one is finshed. You can read more about this here: http://msdn.microsoft.com/en-us/library/dd537612.aspx

And by the way, you really should not run heavy calculations on the UI thread itself. If you decide to use tasks - that would be fine. Otherwise , you need to create background thread and do the work there.

Edit:

After some clarification from the OP , I will try to explain the basics or working with UI and background threads: When you run a winforms/WPF application, all of the user interface events are handled in a single thread - the UI thread. it goes over all of the events and processes them. If long calculation occupy this thread, the UI will become "stuck" and o responsive. see: UI freezes on heavy calculation

That is why, any long calculations should be done on another thread, in the background. In the above post's answer there is an example on how to do this.

Community
  • 1
  • 1
omer schleifer
  • 3,897
  • 5
  • 31
  • 42
  • Can you show me some example code of this formed around the way I'm trying to do it? – user2476620 Jun 12 '13 at 04:29
  • Please clarify what it is you are trying to do. just run some tasks one after another? if that is the case why do you need timers at all? you might as well do all the work on a single (non-UI) thread. or am I missing something? – omer schleifer Jun 12 '13 at 04:32
  • a non-UI thread? I'm very new to C#, just converted over from VB.NET. May I have some links to all of these methods? Thanks for your support. – user2476620 Jun 12 '13 at 04:35
  • Thanks Omer, this is perfect. – user2476620 Jun 12 '13 at 04:46
0

You could use the System.Threading.Timer. You would then make use of its single shot capability (see Change method). Such you may chain several timers.

The callback of this timer runs on the thread pool so your UI doesn't freeze.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51