1

Let us consider a method which changes the string contains value often . I need to create thread which runs for every 1 min for getting a values from a string .

Is it possible?

I have tried following code which sleeps the entire process other that particular thread:

System.Threading.Thread.Sleep(10000);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
GowthamanSS
  • 1,434
  • 4
  • 33
  • 58

5 Answers5

5

If you wand to run a threaded process at a defined period of time the System.Threading.Timer class will be perfect

var timer = new System.Threading.Timer((o) =>
{
    // do stuff every minute(60000ms)

}, null, 0, 60000);

However if you are updating any UI code from this thread dont forget to invoke back on the UI thread

WPF:

var timer = new System.Threading.Timer((o) =>
{
    Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
    {
        // do stuff WPF UI safe
    });

}, null, 0, 60000);

Winform

var timer = new System.Threading.Timer((o) =>
{
    base.Invoke((Action)delegate
    {
        // do stuff Winforms UI safe
    });

}, null, 0, 60000);

Example:

private void StartUpdateTimer()
{
    var timer = new System.Threading.Timer((o) => 
    { 
        string ss = "gowtham " + DateTime.Now.ToString(); 
        Response.Write(ss); 
    }, null, 0,1000);
}
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • +1 Nice answer. However, if `do stuff` is playing with the UI then you will also need to get on the UI thread. See http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call – Richard Schneider Jan 09 '13 at 06:19
  • +1 timers are much easier and safer. Hopefully OP can use this approach instead of diving in multithreaded code. – Alexei Levenkov Jan 09 '13 at 06:23
  • no +1 from me timers are evil and bad idea and should be banned. – Nahum Jan 09 '13 at 06:24
  • @Nahum Litvin, if you want to run something every minute/hour etc, timers are the best choice, sleeping a background threads for long periods of time is just silly, unless you have a olympic sized thread pool :) – sa_ddam213 Jan 09 '13 at 06:33
  • my question is when condition is like this string ss = "gowtham " + DateTime.Now.ToString(); var timer = new System.Threading.Timer((o) => { Response.Write(ss); }, null, 0,1000); will for every 1ms value will be changed – GowthamanSS Jan 09 '13 at 06:37
  • @ sa_ddam213 I disagree if action takes more than the interval you are into some real trouble. I saw this happen more than once with unexpirienced programers. – Nahum Jan 09 '13 at 06:37
  • Thats why the c# gods created `lock`, but its user preference, but for updating a string every minute this will be the best solution for OP, but for long running tasks timers can be painful I will agree :) – sa_ddam213 Jan 09 '13 at 06:41
  • @GowthamanSS since you have already set `ss` it will not change, you will have to set `ss` inside the timer delegate. ` var timer = new System.Threading.Timer((o) => { string ss = "gowtham " + DateTime.Now.ToString(); Response.Write(ss); }, null, 0,1000);` – sa_ddam213 Jan 09 '13 at 06:48
  • @sa_ddam213 can you provide me any sample for checking ur query – GowthamanSS Jan 09 '13 at 07:16
  • What kind of sample do you want? WPF, Winforms, Console what do you want the sample to do? – sa_ddam213 Jan 09 '13 at 07:25
  • @sa_ddam213 i am using it in class library and a sample which works for my problem to solve – GowthamanSS Jan 09 '13 at 07:26
  • can you post some code in your question because I don't know what you are trying to do, what is `Response.Write` – sa_ddam213 Jan 09 '13 at 07:35
  • added example, to start the timer just run `StartUpdateTimer() ` and it will run the code inside every minute. – sa_ddam213 Jan 09 '13 at 08:30
1

Use:

new Thread(delegate()
    {
         while(true)
         {
             // Do stuff
             Thread.sleep(60000);
         }
    }).Start();

60 000 miliseconds is a minute

Thread.sleep puts the current thread to sleep

ZombieSpy
  • 1,376
  • 12
  • 23
  • Not sure how sleeping for 60 seconds better that sleeping for 10 when OP explicitly said that it blocks whole process due to sleaping on UI thread? – Alexei Levenkov Jan 09 '13 at 06:15
  • @AlexeiLevenkov he should not call sleep on the main-thread ofc, but in the background thread. – dognose Jan 09 '13 at 06:18
1

Sleep does not start new thread, it blocks current thread (in your case UI thread) for given number of milliseconds.

Based on your description you want to start new thread and can sleep in that thread. Also it may be easier to use timers. Complete sample and information on Thread object avaialbe in MSDN Thread article:

new Thread(ThreadFunction).Start(); 
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

C# or more spesificly .NET supports MULTITHREADING.

when you use Thread.Sleep() it will disable the one thread that used Thread.Sleep()

here is an exmaple of using the 'TPL' to lunch athread that samples the string every 60 seconds

System.Threading.Tasks.Task.Factory.StartNew(
()=>
{
System.Threading.Thread.Sleep(60000);
 ReadString()}
)

you should keep in mind that you need to protect your string from RACE CONDITION

use C# lock for this

Nahum
  • 6,959
  • 12
  • 48
  • 69
0

Instead of starting a new thread every 60 seconds, use one thread, that sleeps after finishing until the next run. Something like this:

Class Main{

public void startObserverThread(){
   Thread t = new Thread(this.observerThread);
   t.start();
}

private DateTime lastRun = null;
public void observerThread(){
   if (lastRun == null || DateTime.Now.Subtract(lastRun).Seconds >= 60){
       lastRun = DateTime.Now;
       //do thread work.
   }else{
       //check every second, if time elapsed
       Thread.sleep(1000);
   }
}

}

Change the waiting time if it needs to be more accurate. The big advantage vs resheduling a new thread at the end of the thread is, that you dont need to take care about the execution time of the task itself. If it takes 10 seconds, the thread will sleep for like 50 seconds. if it takes 50 seconds, the thread only sleeps 10 seconds after completing the task work.

dognose
  • 20,360
  • 9
  • 61
  • 107