Alternative to Thread.Sleep in C#?

I have a code which when run, it executes series of lines in sequence. I would like to add a pause in between.

Currently, I have it like this

//do work Thread.Sleep(10800000); //do work

This however freezes the software, and I think it's because sleep time is way too long. I searched online and I found another work around called Timer. Can someone show me a sample code for Timer which works just like Thread.sleep?

Thank you in advance.

Edit : I need the software to wait for 3 hours before proceeding with rest of the code execution. This software is meant to communicate with machines, and I cannot let the rest of the code execute while waiting for 3 hours.

-------------Problems Reply------------

Your software would freeze if that sleep is on the main thread. Keep in mind the parameter is in milliseconds. 10 800 000 milliseconds = 10 800 seconds

Another way to pass the time is to pass a TimeSpan object instead. Ex:

// Sleep for 10 seconds
System.Threading.Thread.Sleep(new TimeSpan(0, 0, 10));

As for timer:

You can use System.Timers.Timer;

Timer timer = new Timer();
timer.Interval = 20; // milliseconds
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.AutoReset = true; // if not set you will need to call start after every event fired in the elapsed callback

Please see this MSDN reference on the System.Threading.Timer class. There is a great explanation, all of the class members, and some sample code for you to follow when testing/learning.

Mind you, though, the Timer should be used when you want to fire an event at a certain interval. If you are just looking to pause execution of your application, then you should go with Thread.Sleep(). However, as many others have pointed out, you are causing your thread to sleep for an extended amount of time.


private DispatcherTimer Timer;
public Constructor
Timer = new System.Windows.Threading.DispatcherTimer();
Timer.Tick += new EventHandler(Timer_Tick);
Timer.Interval = new TimeSpan(0,0,10);

private void Timer_Tick(object sender, EventArgs e)
Timer -= Timer_Tick;
Timer = null;

Your problem is that you're blocking the main thread of your application, which is responsible for keeping the ui running. You shouldn't do this. Instead use a timer - the Forms one is probably easiest in a Forms app, or consider BackgroundWorker. (For such a long wait a timer is probably more suitable)

The Thread.Sleep is what you want to use for this, you may want to use a more reasonable sleep period than 3 hours though.


After reading some of the comments, Thread.Sleep is probably not what you want. Use a System.Threading.Timer instead as others have suggested.

Have a look Thread.Sleep(300) not working correctly

Probably you need to use the "Dispatcher". Have a look here as well

Thread.Sleep would typically be used to pause a separate thread, not in the main thread of your app.

Timer would typically be used to periodically cause the main thread to stop its normal operations and handle an event.

Either method can be used to periodically perform a function after a certain time interval.

What I wouldn't do is ask the main thread to sleep for 3 hours.

I think you should use a Monitor. It helps you to put a wait on objects and release the lock when you need to continue running the program.

You should find your answer here: Safe Thread Synchronization

You're sleeping the thread for 10800 seconds, or 3 hours. Thread.Sleep() is designed to freeze your thread, stop anything from working in the software for that duration. In this case, the duration is 18 minutes. What are you trying to do?

Category:c# Views:0 Time:2012-02-02

Related post

  • Alternative to Threads 2010-02-05

    I've read that threads are very problematic. What alternatives are available? Something that handles blocking and stuff automatically? A lot of people recommend the background worker, but I've no idea why. Anyone care to explain "easy" alternatives?

  • Alternative to thread for small tasks without freezing the GUI 2011-01-25

    I'm writing a small application, composed by a gui and a couple of buttons. When the user clicks one of them, the program must download a webpage, do a couple of matching and return a value to the gui. The question is, I must start a new thread every

  • Alternative to threads for implementing massive parallel calculation engine in c# or java? 2012-04-29

    Suppose there is a need for building a spreadsheet-like engine that needs to be ultra fast, each cell dependencies could be on parallel calculation branch. Could thread be created for each parallel branch ? Isn't thread costfull in term of memory. Ea

  • Alternatives to Thread.Sleep() for simulating pauses 2009-09-21

    So Thread.Sleep() is bad ( Is there any recommended alternative to simulating a pause in execution of a program? Eg a loop? Although I s

  • Alternative to Thread.Sleep() before socket read 2011-01-27

    I'm using this FtpClient library to connect to mainframe from WinForms application. I'm using thread.Sleep for the thread to wait for the response before it starts reading, otherwise it freezes. Is there an alternative to do this? public void Login()

  • Alternatives to Thread.Sleep() 2011-03-24

    Every N minutes we want to run through a list of tasks. So we've created a task executor with a do { DoWork(); }while(!stopRequested) Now we want to have a pause between work cycles. Everyone seems to think Thread.Sleep() is the devil. I've seen ment

  • C# - Alternative to Thread.Sleep? 2011-03-27

    I'm doing all this in C#, in Visual Studio 2008. I want to slow down the work of my algorithm so that the user can watch it's work. There is a periodic change visible at the GUI so I added "thread.sleep" after every instance. Problem is that "thread.

  • Thread Safe Alternative to Thread.Sleep that allows browser activity in c# 2011-11-30

    I need a simple wait function that allows browser events to process and is thread-safe. A collegue said never to use DoEvents when working with multiple threads. I notice that when I use Thread.Sleep(10000); my browser activity pauses until the sleep

  • Java - alternative to thread.sleep 2012-02-04

    I have a requirement to pause a while loop for a specific number of milliseconds. I have tried using Thread.sleep(duration) but it is not accurate, especially in a looping scenario. Millisecond accuracy is important in my program. Here is the algorit

  • Alternative to Thread.Suspend() method 2012-04-18

    Thread.Suspend() method is obsolete as you know. I want to suspend thread immidiately when button click event comes. I used Thread.Suspend() and it works perfect but everyone suggest that using Thread.Suspend() method is not a good method to suspend

  • Java Concurrency: Alternative to Multi Threading (working with non thread safe environment) 2012-02-16

    I am working with a 3rd party proprietary library (no source code) which creates instances of a non thread safe component. Does this mean that I shouldn't use multiple threads to run jobs in parallel? Running each job in it's own JVM crossed my mind

  • Re-creating threading and concurrency knowledge in increasingly popular languages 2009-01-13

    I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for

  • How independent are threads inside the same process? 2009-01-22

    Now, this might be a very newbie question, but I don't really have experience with multithreaded programming and I haven't fully understood how threads work compared to processes. When a process on my machine hangs, say it's waiting for some IO that

  • How do I safely populate an array from one thread while reading it in another in Objective-C? 2009-06-07

    First off I'm not that familiar with using threads and i'm learning on the fly. I have an array that is being used in thread a and being populated in thread b. What I want to do is find the best practice for waiting for the array to be populated from

  • Why might threads be considered "evil"? 2009-07-28

    I was reading the SQLite FAQ, and came upon this passage: Threads are evil. Avoid them. I don't quite understand the statement "Thread are evil". If that is true, then what is the alternative? My superficial understanding of threads is: Threads make

  • Is LWP::UserAgent not thread-safe? 2009-12-03

    I'm running 40-or-so threads with the following subroutine: my $app = shift; my $ua = LWP::UserAgent->new(); $ua->timeout(5); my $response = $ua->get($$app{'watch_url'}); my $new_md5; if ($response->is_success()) { $new_md5 = md5_hex($res

  • Thread.currentThread().sleep(time) v/s Thread.sleep(time); 2010-07-24

    Possible Duplicate: Java: Thread.currentThread().sleep(x) vs. Thread.sleep(x) whats the difference between... Thread.currentThread().sleep(time) and Thread.sleep(time); one more thing is there anyother method by which i can delay in program without u

  • How is Node.js inherently faster when it still relies on Threads internally? 2010-09-02

    I just watched the following video: Introduction to Node.js and still don't understand how you get the speed benefits. Mainly, at one point Ryan Dahl (Node.js' creator) says that Node.js is event-loop based instead of thread-based. Threads are expens

  • measure time .net thread spent waiting for IO 2011-01-25

    This is a continuation to How much time spent in a .NET Thread? I know how I can measure cpu time of a thread (, but I don't know how to measure IO wait of a thread. Thread waits for IO, ge

Copyright (C), All Rights Reserved.

processed in 0.179 (s). 11 q(s)