ahmed tota 2006
ahmed tota 2006

Reputation: 19

timers [Delay without Freezing the app !] C#

I'm trying to make an application that every 10 minutes executes 10 different SQL queries, and between each SQL query there should be a short delay (for example, 1 second).

If I try to use Thread.Sleep(1000);, the other timers stop and the whole application freezes.

Any idea how to do this without freezing the application or stopping other timers?

Upvotes: 0

Views: 894

Answers (3)

Guvante
Guvante

Reputation: 19203

You can use threading to spin up another thread which performs those actions.

The simplest form would be System.Threading.ThreadPool.QueueUserWorkItem(WaitCallback)

It takes a delegate which consumes a single object and performs the task.

e.g.

private void Worker(object ignored)
{
    //Run first query
    Thread.Sleep(1000);
    //Run second query etc.
}

//The following code is where you want to start the process
//For instance in response to a timer
ThreadPool.QueueUserWorkItem(Worker);

Upvotes: 5

David Thielen
David Thielen

Reputation: 32926

I think what you're saying is every 10 minutes you need to fire off 10 SQL queries, and you want a pause between each.

First question, do you want one to complete before the next starts and add 1 second between them? Or start each 1 second apart but all may be running at the same time?

And are you running these in your main UI thread (bad idea) or a worker thread?

Based on your question I think you're running them in your main thread. Instead create a worker thread that fires once every 10 minutes. Without the worker thread your system will freeze anytime a query takes awhile.

If you want 1 second between completion of one thread and start of the next, you can put the Sleep(1000) call in the worker thread.

If you want 1 second between the start of each, you need 10 worker threads. The first will set the second to fire in 1 second, then call it's query. The second will set the third to fire in 1 second, then start it's query.

Upvotes: 0

Adel Khayata
Adel Khayata

Reputation: 2836

For each timer's execute, you should start a new thread to execute your SQL Queries code.

Upvotes: 1

Related Questions