I have a console app. I need to implement a do while that loop infinitely and a thread that at every 3 seconds returns a list of items from a page. How can I do that? I have a methold called getId( string URL) . how do I implement the thread in the do while?
Using System.Timers.Timer class:
string url = "www";
System.Timers.Timer timer = new System.Timers.Timer(3000);
timer.Elapsed += (o, e) => this.GetId(url);
timer.Start();
Timer is designed for use with worker threads in a
multithreaded environment. Server timers can move among threads to
handle the raised Elapsed event, resulting in more accuracy than
Windows timers in raising the event on time.
The Timer component raises the Elapsed event, based on the value of
the Interval property
I would not use a timer - what happens if the item retrieval takes longer than three seconds?
Can you live with a sleep(3000) loop?
Rgds,
Martin
Related
I am facing a issue when used to system.timers.time, i have a running process in my application.
with timer called my process start, but i want to use that process within the thread only.
because every time timer elapsed event called the new thread has been generated, but i want to prevent this and only using single thread in a process.
Here is my code.
Public void Watcher()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 3000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
Public void OnTimedEvent
{
// process code here
}
Here, after every 3 seconds OnTimedEvent called and new thread created, but i don't want to create new thread every time.
So, how to prevent this, any idea?
If you have a UI you should simply use forms timer or dispatch timer. If you do not have a UI you can set the SynchronizationObject of the timer. This will be responsible for marshaling the execution to the right thread.
I would probably skip the synchronization object, and just do the marshaling in the event handler of the event.
In either case you will need some kind of message loop if you do not have a UI. This would have a threadsafe queue where the thread takes a message and process it, one at a time. For example, using a blocking collection of Action.
As mentioned by #MindSwipe in the comments. A new thread will not be generated per event. It will simply take threads from the threadpool. So the number of threads used should be fairly constant. The main reason for moving all execution to one thread is because it can make threadsafety easier to manage.
I need to set up a simple elapsed Timer in C# (MonoBehavior) that calls a method when complete, but can also be cancelled before finishing. If cancelled or stopped, it automatically resets its interval. I don't need anything fancy like threading.
Reading over the documentation on C# Timers https://msdn.microsoft.com/en-us/library/System.Timers.Timer%28v=vs.110%29.aspxstill a bit confused. For instance, when you set mytimer.Enabled=false does it also reset the timer back to 0? Perhaps I should be looking at Coroutines instead?(this is for Unity)
In AS3 I would do something like this
private var _delayTimer:Timer;
//create a Timer object that runs once for 1 second
_delayTimer = new Timer(1000,1);
//add handler
_delayTimer.addEventListener(TimerEvent.COMPLETE, onDelay);
//start timer
_delayTimer.start();
private function onDelay(e:TimerEvent):void{
trace('delay finished!);
}
//some other method to interrupt-stop and reset the delay timer
private function foo():void{
_delayTimer.reset();
}
By using System.Timers.Timer, you are using multi-threading - it's quite likely this is not what you want.
Instead, you probably want System.Windows.Forms.Timer - this will post the timer event back on the UI thread (if you're using Windows Forms, of course).
You can use Start and Stop the way you want, because there's actually no ticking clock - it just registers a callback from Windows in the future, basically.
Relevant piece of documentation from MSDN:
Calling Start after you have disabled a Timer by calling Stop will cause the Timer to restart the interrupted interval. If your Timer is set for a 5000-millisecond interval, and you call Stop at around 3000 milliseconds, calling Start will cause the Timer to wait 5000 milliseconds before raising the Tick event.
I have the following scenarios using System.Timers.Timer.
Create a Timer object and assign the method
_JobListener.Enabled = false;
_JobListener.Elapsed += (this.JobListener_Elapsed);
Within JobListener_Elapsed, I created another thread to run some functions.
JobListener_Elapsed
{
//stop the timer
_JobListener.Enabled = false;
System.Threading.Thread pollThread = new Thread(JobListener_ElapsedAsync);
pollThread.Start();
//join to the main timer thread
pollThread.Join();
//restart the timer
_JobListener.Enabled = true;
}
Within JobListener_ElapsedAsync, I log the timer Enabled status.
private void JobListener_ElapsedAsync()
{
try{
log Timer.Enabled
some other code
}finally
{
_JobListener.Enabled = true;
}
}
However, I can see some times, it can see the timer status to be true, which is wrong. The timer should be stopped when JobListener_ElapsedAsync is running.
Any idea?
There are two main classes of timer in the .NET Framework: thread timers, and window timers.
System.Threading.Timer is the basic class for thread timers. This wraps the Windows waitable timer object. The Tick event is fired on the ThreadPool. It does not check whether all handlers for a previous Tick have returned before firing Tick again. The timer should fire on time - it is not delayed.
System.Windows.Forms.Timer wraps the Windows SetTimer API. The Tick event is fired on the thread that creates the timer. If that isn't a UI thread it won't actually fire. Timers are the lowest priority messages; they are only generated by GetMessage/PeekMessage when no other messages are outstanding. Therefore they can be delayed significantly from when they should be generated.
System.Timers.Timer wraps System.Threading.Timer. If you have set its SynchronizingObject property to something, when the underlying timer fires, it will use ISynchronizeInvoke.Invoke to get onto that object's thread (analogous to Control.Invoke - indeed Control implements ISynchronizeInvoke). It blocks the thread pool thread in the process. If SynchronizingObject is null it just fires the Elapsed event on the thread pool thread. The only real use for this class is if you need timers for UI components to be fired on time. If you don't need to synchronize, use a System.Threading.Timer instead.
If you need to ensure that a previous Tick event is fully handled (all handlers have returned) before the next one is started, you need to either:
Make the timer one-shot rather than periodic, and have the last handler set up another shot when it finishes executing
Use a lock or Monitor to prevent two threads entering the handler (but you could use up all threads in the thread pool)
Use Monitor.TryEnter to only enter the handler if the previous one has finished (but you could miss some Ticks).
In my WPF application i use 3 different DispatcherTimers.
One is for displaying the current time
One is are for running a DB query every 5 sec
The third one refreshes a value for a custom button every 1 sec
When my program is running there are a lot of delays / freezes.
For example the time starts ticking correctly but on a sudden the value freezes up and after the freeze the time gets incremented by +3 seconds for example.
I am getting this behavior over my entire application.
What is the proper way to solve this problem with several timers?
EDIT:
I am having problems to replace a DispatcherTimer with a Timer from System.Timers namespace.
//new code with timer
timerW = new Timer();
timerW.Elapsed += new ElapsedEventHandler(timerWegingen_Tick);
timerW.Interval = 5000;
timerW.Start();
//OLD Working Code
timerW = new DispatcherTimer();
timerW.Tick += new EventHandler(timerWegingen_Tick);
timerW.Interval = new TimeSpan(0, 0,5);
timerW.Start();
Error : "The calling thread must be STA, because many UI components require this."
Best regards.
the DispatcherTimer is executed on the UI thread. So if the UI thread is busy for more than the interval, it will be executed when the UI thread is free to do so.
If you need more precise scheduling, you should go for a time than runs in the background (System.Threading.Timer, System.Timers.Timer). But don't forget about marshalling then.
hth,
Martin
I guess this is because they all are running on same thread.
Use System.Threading.Timer and when updating UI use the SyncronizationContext.Syncronize to run the updating code in.
Don't forget to get the context from SyncronizationContext.Current on the UI thread.
I have a program written in C# (Visual Studio), that works on a tray.
I want it to do one action every 10 minutes.
I have following code now:
while(true)
{
Thread.Sleep(10000);
// my stuff
}
But it doesn't work. It freezes a program.
You should use the timer object and not create a while loop.
System.Timers.Timer _timer = new System.Timers.Timer();
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
//30 seconds
_timer.Interval = 30000;
_timer.Start();
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//do your logic
}
Thread.Sleep makes the calling thead Sleep for an X ammount of time. If this thread is the frontend thread (the one responsible for handling messages), it will indeed freeze the application since any message for handling events or repainting wont be handeled untill the Thread wakes up again and gets a chance of handling the messages.
What you should do is schedule this logic every 10 seconds.
Drop a timer on your form and specify it to run each 10 seconds. Within the Tick event, call your custom action.
Thread.Sleep "stops" the current thread. if you only have one thread, everything is paused.
What do you want to achieve ?
Perhaps you need a second thread, or perhaps the better solution a timer which triggers a action every 10 minutes
s. Task.StartNew() or ThreadPool