简体   繁体   中英

Issue regarding Thread.Sleep() for 2hours in c#

I am working on .net windows application.

I am using System.Threading.Thread.

In a single form using five(5) threads. I have a code which when run, it executes series of lines in sequence. I would like to add a pause in between.

For that i am using

Thread.Sleep(10800000)

of 3 hours

But I checked in debug mode, after executing line of

Thread.Sleep(10800000)

My debug not goes to next line or next line never executes even after waiting for 4 hours.

I am using this Thread.Delay in other thread not in main thread. This delay requires because, i send a command to configure setting to a hardware, that setting requires minimum 3 hours to complete.

That's why i am using this

Thread.Delay(10800000)

Means my onward code is proceed only after waiting for 3 hours.

Can any one help me?

Thread.Sleep is not designed for long sleeps. You should consider using somthing like System.Threading.Timer .

Provides a mechanism for executing a method on a thread pool thread at specified intervals.

You can give it a first run time of midnight, and have it go off every 24 hours. the Timer(TimerCallback, Object, TimeSpan, TimeSpan) constructor is exactly what you are looking for.

One would argue that even using a timer is not the best tool for the job. You may want to consider using Windows Task Scheduler (TS) instead. With TS, you can setup a schedule to say run your app and carry out the workflow, or if your program must run all the time, trigger another process that communicates with your app somehow.

If the process is not doing anything until the next interval then it's best to just simply kill the app . That way you won't be wasting threads or processes twiddling their thumbs over exorbitant delays waiting for the next interval to do something.

You can use the Microsoft Task Scheduler v2 COM Library from c# to setup your schedules or do so manually from the TS UI itself.

I suggest using a timer instead of Thread.Sleep or Delay. In place of Thread.Sleep start a timer with timeout of 3 or 4 hours depending on your needs which then would send needed command.

System.Threading.Timer might do the job

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM