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);

5 Answers 5

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);
}
Sign up to request clarification or add additional context in comments.

13 Comments

+1 Nice answer. However, if do stuff is playing with the UI then you will also need to get on the UI thread. See stackoverflow.com/questions/253138/…
+1 timers are much easier and safer. Hopefully OP can use this approach instead of diving in multithreaded code.
no +1 from me timers are evil and bad idea and should be banned.
@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 :)
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
|
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(); 

Comments

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

2 Comments

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?
@AlexeiLevenkov he should not call sleep on the main-thread ofc, but in the background thread.
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

Comments

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.

1 Comment

how u will declare null value to datatime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.