is there anyway to sleep the some particularthread by name or some any other source
in case I've two threads
Thread call = new Thread(() => open_page(txtbx_1.Text));
call.Start();
Thread call_2nd = new Thread(() => open_page(txtbx_1.Text));
call_2nd.Start();
I want to sleep call and call_2nd for at least 15 minutes(but don't want to sleep the main Thread.
Thanks
No - you can't ask another thread to sleep. Apart from anything else, at the time when you want it to sleep it may hold a lock or other resource which really shouldn't be held while sleeping.
You'd have to do this cooperatively, with some sort of shared data between the threads indicating what you want to sleep and for how long. Alternatively, schedule a timer to only start the relevant activity after a certain length of time.
Why would you want a thread to sleep unless it was otherwise going to do something you didn't want it to do? And why would you ever code a thread to do something you didn't want to do?
If you're asking this question, something is very wrong somewhere in your design or implementation.
Yes, but in a different way than you might think.
Have the target thread(s) you want to sleep regularly check an manual-reset event. That event (flag) is cleared by the controlling thread whenever the target thread is supposed to sleep, otherwise it is always set. If you want the target thread(s) to sleep only for a certain amount of time, use that value as the wait timeout.
if the event is set (no sleep), the wait is satisfied immediately and execution continues
if the event is cleared (sleep), the target thread(s) stops until
the timeout (15 minutes = 15 * 60 * 1000 ms) elapsed
or the controlling thread sets the event again within that time frame
If you need to check whether or not the target thread(s) is in the waiting state, consider another event/flag/counter, set by the target thread(s), and read by the controlling thread.
Related
I have a Timer in my code for some 'x' seconds. The code has multiple threads and there are multiple timers. Now I notice that, my application goes to a hang state after running for some time and from the logs I notice that the timer interval varies. It has increased. How is this possible and can anyone provide a solution for this? Is there any alternative for timer in c#
_timernew = new System.Timers.Timer(10000)
{
AutoReset = false
};
_timernew .Elapsed += (sender, e) => { DoSomething };
_timernew .Enabled = true;
Timers are not precise. The interval is the minimum delay before the event is fired, but you are not guaranteed your timer event will get executed exactly when the interval elapses.
When the interval elapses, the timer queues your even handler to the thread pool. Therefore, the event handler will get executed when there is an available thread in the threadpool to take the handler, and then an available CPU core to actually execute it.
In other words, the more busy the computer is, the more likely delays will happen.
If you need a closer to real-time execution, you must use a dedicated thread and set its priority to high:
Thread myThread = new Thread(MyThreadMethod);
myThread.Priority = ThreadPriority.Highest;
myThread.Start();
Now, however, in your MyThreadMethod, you need to implement a sophisticated mechanism that monitors how much time has elapsed and decide whether you must execute your actual code or not.
You should not just loop and check the time, because that will occupy a single core at 100%. Perhaps you can use the dreaded Thread.Sleep with a smaller interval and check if time has passed. You must use a smaller interval than the one you need at a magnitude of at least 10. Thread.Sleep is not precise, too.
I'll be short and to the point. I basically need a way I can take a timer, check when the timer is up and execute something at the end of it, then loop it. For example (this code isn't serious, just example code) :
Timer1.start();
If (timer1.TimeRanOut) {
Timer2.start()
}
Or some other way to pause the timer without the GUI freezing up (I'll be running some things at a fast pace and freezing would get in the way). I'll be making this more complex by looping the entire process, like :
if (Checkbox1.checked == true; )
{
Timer1.start();
Next If (timer1.TimeRanOut) {
Timer2.start()
}
Next If (timer2.TimeRanOut) {
Timer3.start()
}
And so on. Any solutions?
I would suggset working with Tasks. you set up a task to do something (it can just wait for X seconds, than it is a timer) than you set continueWith to assign a new task to run when the first one is finshed.
You can read more about this here:
http://msdn.microsoft.com/en-us/library/dd537612.aspx
And by the way, you really should not run heavy calculations on the UI thread itself.
If you decide to use tasks - that would be fine. Otherwise , you need to create background thread and do the work there.
Edit:
After some clarification from the OP , I will try to explain the basics or working with UI and background threads:
When you run a winforms/WPF application, all of the user interface events are handled in a single thread - the UI thread. it goes over all of the events and processes them.
If long calculation occupy this thread, the UI will become "stuck" and o responsive. see:
UI freezes on heavy calculation
That is why, any long calculations should be done on another thread, in the background.
In the above post's answer there is an example on how to do this.
You could use the System.Threading.Timer. You would then make use of its single shot capability (see Change method). Such you may chain several timers.
The callback of this timer runs on the thread pool so your UI doesn't freeze.
I have a program that starts constantly juggles between 3 separate timers.
The main thread of my application has a while loop which constantly checks if a global variable has been set to true and if it has, it will stop one timer and launch two other ones - one continuously, another to stop it automatically if it isn't commanded to stop for whatever reason.
This while loop has a condition of (1==1) so that it runs forever.
In the task manager (XP) I see that my program is using up 50% of cpu on a more or less idle system.
Is there a way to decrease that number by decreasing the speed of the while loop or something?
Thanks.
Is there a way to decrease that number by decreasing the speed of the while loop or something?
Just stop doing a busy loop. There are better ways of coordinating events between threads. Consider using Monitor.Wait/Pulse, or AutoResetEvent / ManualResetEvent. Basically, the thread that sets the global variable should signal that it's done so. Alternatively, if your main thread wouldn't be doing anything else, why not add a normal C# event so that whenever the variable is changed, the event is raised and the appropriate action can be taken?
Your program performs busy waiting, which is a bad practice. You should change your logic so that instead of looping, you block on some kind of synchronization primitive (also known as wait handle).
Blocking on a wait handle is not an option for the UI thread, so you would have to create three threads in total and implement the scheme like this:
The UI thread does not concern itself at all with what other threads to. No looping, no sleeping, no blocking.
The new "controller" thread would start the existing "worker" thread and then immediately block (e.g. on an event that is not signaled). It will remain in this state, without consuming CPU, until the event is signaled (i.e. the "worker" completes).
The "worker" thread would run its course and then signal the event.
Is there a way to decrease that number by decreasing the speed of the while loop or something?
Yes, you could insert a call to Thread.Sleep(n). With a granularity of ~20 ms.
But the far better option would be using a Waithandle.
Your main thread would Wait on the handle and the end of the timer code would signal it to wake up.
You need to sleep the threat for a given number of ms. Look at the Thread.sleep() function and place it within your while loop.
The easiest way to slow down a loop like this is to just add a System.Threading.Thread.Sleep(100); For every iteration the process will sleep for 100 ms and it will not use 50% cpu anymore.
You can use Threads instead of Timer it costlier than Thread. Or Please check the thread state of your time which stopped before start another. You can improve performance by cutting down your code logic.
Hope this will helps you. :)
While the answers here aren't wrong per-say, They don't really address a lot of issues with doing while(true) loops which is what while(1==1) is.
First of, even if the loop is running the entire time your application is in use, you will want to shit it down at some point, say when the user exits your application, because if you have a thread with a constant loop, even if the user closes the UI window, the process will remain until the thread exits (which is never in a while true loop) or until the user becomes wise and closes it from the task manager.
You COULD solve this by putting a true conditional in the while conditional check that references a accessible property outside the loop.
Example:
private bool RequestExit = false;
private Thread MyLoopThread;
private void MyLoop()
{
while (!RequestExit)
{
//Do stuff!
Sleep(1);
}
}
public void StartLoop()
{
RequestExit = false;
MyLoopThread = new Thread(MyLoop);
MyLoopThread.Start();
}
public void StopLoop()
{
RequestExit = true;
}
That is the bare-bones and doesn't even get into avoiding double launches or double shutdown events.
A much cleaner way would be to set an arbitrary interval that you want to pool at, 10ms or so should do just fine for pretty much any real time event, and trigger an method to fire at that interval.
private Timer DoStuffTimer;
private void DoStuffMethod(object obj = null)
{
//Do stuff!
}
public void StartLoop()
{
DoStuffTimer = new Timer(DoStuffMethod,null,10,10);
}
public void StopLoop()
{
DoStuffTimer.Dispose();
}
First, sorry for my bad english writing.
Suppose that we have a win form (C#) that has a timer. The timer interval has been set to 60000 milsec. So its tick event will be fired every 1 milute. Suppose we have written a method that handles tick event called Timer1_Tick. What if the job needs more that 1 minute to complete?
You've got several options, here's four I can think of:
Abandon the current job to start the new one. The big downside of this one is, of course, if the current job can't be stopped.
Wait for the current job to finish before starting the new one. This might leave you with a queue of pending jobs if each one takes more than a minute.
Don't start the new job. Let the current one finish and then wait for the next timer interval to start the new job.
Increase the interval between jobs. This is just putting off the problem.
There is no right answer. You'll have to work out what's best and works for your situation.
I'd go for #3 as my first solution.
Setup a flag that will allow you to check if the long running job has finished and only run the job if it has finished. Don't forget to reset the flag after finishing the long running job:
// field
private bool finishedWork = true;
public void Timer1_Tick(Object o, EventArgs e)
{
if (finishedWork)
{
finishedWork = false;
// do work
finishedWork = true;
}
}
Another option is to simply disable the timer between operations:
public void Timer1_Tick(Object o, EventArgs e)
{
if (finishedWork)
{
Timer1.Enabled = false;
// do work
Timer1.Enabled= true;
}
}
So set a flag when you start the job and check the flag when the timer fires. If the flag is set, do nothing in the timer handler. Remember to clear the flag when the job completes.
Are you spinning off a worker thread to do the job?
Another timer event will likely be queued, causing Timer1_Tick to be called again almost immediately after it returns. (IIRC, though, timer ticks are one of the lowest priority messages, so it'll probably handle any other messages it's had queued up to that point first, except maybe paint messages).
Note, if your function takes longer than 2 minutes to run, it's possible (read: likely) that only the latest tick will be in the queue.
If your tick processing takes longer than the timer interval, you should look into raising the interval. Either way, you should probably be doing the work in a background thread and making sure you don't start another thread if the last tick's task isn't done. Otherwise you could end up with hordes of threads all slowing each other down til your program collapses under its own weight.
Store the current state of the process in a field or property and start the process only if the state is no "running".
Disable the timer at the start of Timer1_Tick and then enable it again afterwards?
There are multiple types of Timers in .Net: One is in a System.Timers namespace, another is in System.Windows.Forms namespace and another in System.Threading.
The System.Windows.Forms.Timer control is based on UI thread and message loops, meaning it will queue the timer events and if your handler exceeds the interval, it will be called immediately after ending.
The other two timers are based on threading, and are very accurate. They will reenter you handler after the time elapsed.
I want to wait for 15 seconds, then the control should resume from the next statement.
I don't have anything else to do while waiting (Just waiting).
I know that there is Thread.Sleep(15000). What I don't know is the best method to wait? What are the limitations of this?
The code would be like this:
Method()
{
statement 1;
statement 2;
//WaitFor 15 secs here;
statement 3;
}
The disadvantage of Thread.Sleep is if this is called in your GUI thread (the thread that processes GUI events, for example, a button click handler method, or a method called from a button click handler, etc.) then you application will appear to freeze and be nonresponsive for those 15 seconds.
It would be perfectly fine if you had explicetly created a seperate thread and called Thread.Sleep in it, assuming you don't mind that thread not doing anything for 15 seconds.
The alternative would be to create a Timer and start it after stmt 2, and place stmt 3 in the Tick event handler for the timer, and also stop the timer in that handler.
This may not be a direct answer to your question. I would say check whether your process flow is better than checking whether the code is better ;-)
Are you waiting for 15 seconds just to make sure stmt2; is complete? If so then adding an handler, as soon as stmnt 2 is executed, would be a better solution (?)
You can also use a timer to wait. Thread.sleep is a bad design. We have a similar question which talks about the comparison using Thread.sleep and Timer.
Try something like the following:
void Method()
{
console.log('statement 1');
console.log('statement 2');
var timer = new System.Threading.Timer(
o => // timer callback
{
console.log('statement 2');
},
15000, // Delay
0 // Repeat-interval; 0 for no repeat
);
}
Syntax is C# 3.0, uses a lambda expression to effectively create a closure around statement #3. With this, you could use any local variables of Method. A thing to note, however, is that with this method, or any other timer-based method...the function will return immediately after creating the timer. The function won't block until the Timer executes. To achieve that, the only thing I can think of is to actually use threads and make Method() block on a signal (i.e. WaitHandle, ResetEvent, etc.) until the timed call on the other thread completes.
Thread.sleep seems a sensible thing to do if there isn't anything else to do while waiting.
It puts the thread to sleep for that time so it doesn't use any CPU resources.
You could always use a timer and then execute code after the set duration. However, if you don't actually have to do anything and just want to wait at a particular point in code, then I think Thread.Sleep(150000); is sufficient.
[Edit: spelling]
If you always want to wait for a given time, then Sleep is useful. Obviously you shouldn't do this on a thread where timely responses are expected.
Keep in mind that your thread will sleep for the duration in all cases. If for some reason you want the thread to resume sooner, you're better off using signaling or callbacks. By using either of these instead of Sleep, you will minimize the needless wait time.
void Method()
{
Statement1();
Statement2();
// Start the timer for a single 15 second shot.
// Keep a reference to it (Mytimer) so that the timer doesn't get collected as garbage
Mytimer = new System.Threading.Timer((a) =>
{
// Invoke the 3rd statement on the GUI thread
BeginInvoke(new Action(()=>{ Statement3(); }));
},
null,
15000, // 15 seconds
System.Threading.Timeout.Infinite); // No repeat
}
I don't sure 100%, but if you really need your method to return after waiting 15 sec, try following:
Method()
{
stmt1();
stmt2();
int time = DateTime.Now.Millisecond;
while (15*1000 > DateTime.Now.Millisecond - time)
{
Thread.Sleep(10)
Application.DoEvents();
}
stmt3();
}