I have a .net Console application which runs infinitely. i have inserted Thread.Sleep() for say 5 minutes to pause my application.
at this point of time i want to display user remaining time (in seconds) for thread to become active and start of application again.
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.startFeed();
}
public void startFeed()
{
while (true)
{
try
{
//My Application which i want to run continously
//when thread enters in run mode
}
catch (Exception xObj)
{
Console.WriteLine(DateTime.Now.ToString()
+ " >> Incoming Message Processing Error. >> "
+ xObj.Message);
}
Console.WriteLine("Waiting For Data......");
Thread.Sleep(300000);
}
}
}
The current structure of your program does not support what you are trying to achieve.
When you call Thread.Sleep(int), it suspends the current thread for the specified time. By default, your program only runs as a single thread, so suspending that thread stops all your code from being run.
You want to display updates to the user, but you also want your worker process to wait for 5 minutes between runs. This means that you will need to create a separate thread for the worker process, and manage that from the thread your program starts with.
One of the simpler ways to do this is to use System.Threading.Timer, as others have suggested. In your case, you could change your code to something like this:
Great, so now you have two threads running at the same time, and calling Thread.Sleep(int) on the one doesn’t influence the other. Note that you don’t need to call Thread.Sleep(int) in ProcessData, because the Timer takes care of that for you.
Finally, you want to show the user exactly when ProcessData will run again. You could do this by adding a DateTime field to your Program class, say
private DateTime _lastRun;and at the beginning of ProcessData, you could set it toDateTime.Now. Then, in the loop in startFeed, you could work out how many seconds are left until the next run using something like_lastRun.AddMinutes(5).Subtract(DateTime.Now).Seconds.There is a lot more that could be said here. As others have hinted, you are writing polling code instead of event-driven code. Polling is usually slower, less efficient and more complex than the event-driven equivalent. However, it depends on your data source being able to notify your code when it has new data to process; polling might be your only option.
There is also a lot to be said about communication between threads. In and of itself, multi-threading is a very tricky subject and is the cause of many hard-to-find bugs. However, for this example, writing to the Console and setting a shared DateTime field should be safe across the two threads.