0

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?

hopper
  • 13,060
  • 7
  • 49
  • 53
  • Once you understand the fact that the timer you are using runs it's code on the UI thread this simply becomes a duplicate of any of the [many "UI Freezes" questions](http://stackoverflow.com/questions/5450353/c-sharp-alternative-to-thread-sleep) with the same solutions. – Scott Chamberlain Jul 25 '13 at 18:02
  • Would you mind displaying some of your code? – Patrick Jul 25 '13 at 18:02

3 Answers3

5

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);
Guvante
  • 18,775
  • 1
  • 33
  • 64
1

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

Adel Khayata
  • 2,717
  • 10
  • 28
  • 46
0

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.

David Thielen
  • 28,723
  • 34
  • 119
  • 193