[2.0] Delay/Wait programmatically
Ok, this is very simple, but I can't figure it out...I want to do one command, wait for x milliseconds then continue on. I do NOT want to use Thread.Sleep because I need the application to be able to do other things during that time...here's how I COULD do it but it's very difficult when you want to do it hundreds of times at different intervals...
//task number1
Timer timer1 = new Timer();
timer1.Interval = 1000;
timer1.enabled=true;
timer1.tick+=new blah blah
//
timer1_Tick(object sender, eventargs e)
{
//task number2
timer1.enabled=false;
}
But I'd like to do it easier, something like this:
//task number1
Delay 1000;
//task number2
if you don't understand...i'll clear it up more.
Re: [2.0] Delay/Wait programmatically
So, you make a queue of tasks:
Code:
private IQueue<SomeTaskClass> queuedTasks;
//the following method of the class will run on a separate thread.
//How its invoked on a separate thread is up to you.
private sub Consume()
foreach (Task task in queuedTasks)
{
//dotask
Thread.Sleep(100);
}
return;
}
There are a few different ways to invoke the method on a separate thread - with most of the solutions built off a more primitive version.
You have at your disposal:
1) Thread.QueueUserWorkItem
2) BackgroundWorker (AsyncEvents in 1.1)
3) Asynchronous delegates
Or using the Windows.Forms.Timer class:
Code:
private IQueue<SomeTaskClass> queuedTasks;
private void timer_tick(..)
{
//de-enqueue one task
queue.Denqueue();
}
Personally, Timer class of Forms may be hard to interpret what code is running where and if setting Enabled will have any affect in the delegated method.
Re: [2.0] Delay/Wait programmatically
Code:
System.Threading.Thread.Sleep(20000);
This code will cause your application's Main thread to wait(sleep) for 20000 milliseconds.
Start another simultaneous thread to do the other work
Re: [2.0] Delay/Wait programmatically
I figured it out...just the way I wanted! And for future reference, anyone can do it like this:
private void Delay(int delayInMilliseconds)
{
TimeSpan timespants;
DateTime datetimedt = DateTime.Now.AddMilliseconds(delayInMilliseconds);
do
{
timespants = datetimedt.Subtract(DateTime.Now);
Application.DoEvents(); // keep app responsive
System.Threading.Thread.Sleep(50);
}
while (timespants.TotalMilliseconds > 0);
}