Andriy Romanchak
Andriy Romanchak

Reputation: 13

c# Thread.Sleep() into Timer

I have the following code:

int i = 5000;
Console.WriteLine("waiting" + i + "miliseconds");
System.Threading.Thread.Sleep(i);
i = 3000;
Console.WriteLine("waiting" +  i + "miliseconds");
System.Threading.Thread.Sleep(i);
Console.WriteLine("finish");

During the sleep my program doesn't respond. How can sleep be translated into the timer functions?

Upvotes: 1

Views: 547

Answers (2)

Justin Pihony
Justin Pihony

Reputation: 67135

You will want to set up an actual Timer in that case. Please see the following example of how to do this. You cannot have your code sleep and move on at the same time. The closest you might have to something like that is if you want to use the C# 5.0 async functionality.

At bare minimum, it sounds like what you are indeed looking for is to write asynchronous programming. If you follow the links or perform your own google searches around these subjects, that should help you.

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124790

During the sleep my programm doesnt respond

Well... yeah, that's what you're telling it to do. You're suspending the main thread, so how could it possibly do anything other than wait?

If you want to launch a background thread or timer you will need to use one of those classes. You do not explain what you are actually trying to accomplish here, so the best advice I can give is to go look up some example code for the BackgroundWorker or Timer classes (there are a few Timer classes, chose the one that best fits what you are trying to do).

Upvotes: 1

Related Questions