Does using Timers have negative effects on applications? - vb.net

I am wondering about the Timer component and what, if any, negative effects occur because of its use or multiple instances of its use. In practice, should there be a limit as to how many timers one should use in a project at one time?

Well, everything is relative but a System.Windows.Forms.Timer is a pretty expensive object. It works by creating a hidden window, required to make the underlying winapi SetTimer() function work. This window is not shared, every timer object gets its own window. A window is in general one of the more expensive operating system objects.
So a very hard upper limit is that you can never have more than 10,000 enabled timers. Windows refuses to allow an app to create that many windows. You should stay considerably south of that limitation, given that all of the windows of all of the processes that run in one desktop session need to share a common heap. Or in other words, creating a lot of windows but staying below the 10,000 quota can negatively impact other processes, it can make them fail when the heap is exhausted.
I'd say a reasonable upper limit hovers around 100. That's a large number of moving parts to keep track of in general, assuming that all of these timers have different Tick event handlers. If they don't then you should tackle this a different way, you only ever need one Timer to measure an arbitrary number of intervals. Roughly the same way you keep appointments with single watch on your wrist. You do so by storing the due times in a SortedList and start the timer only for the first one that's due. When it ticks, work off the entries in the list that have the expired due time and repeat. When you add or remove a due time, stop the timer and restart it when there's a new first due time.

I am assuming you mean the winforms timer object So,
From the Docs:
A Timer is used to raise an event at user-defined intervals. This
Windows timer is designed for a single-threaded environment where UI
threads are used to perform processing. It requires that the user code
have a UI message pump available and always operate from the same
thread, or marshal the call onto another thread.
When you use this
timer, use the Tick event to perform a polling operation or to display
a splash screen for a specified period of time. Whenever the Enabled
property is set to true and the Interval property is greater than
zero, the Tick event is raised at intervals based on the Interval
property setting.
So reading that line by line if you start to pack your application with timers, you are quickly going to be racing the interval events for UI render time.
For instance: You have a clock application that uses a timer to run the clock. At each 1 second interval you have the application render the hands.
In this application you also let the user define as many 'alarms' as they want. Each one creating a new timer that will trigger at set times. These alarms are also allowed to be cyclical. That is to say you allow the user to set an 'alarm' that goes off every x seconds.
Now suppose the user has a long running task (access DB, network resource, calculate PI to 1500 chars etc) that happens on a cyclical alarm. Now suppose the user has 10 long running tasks that need to happen in order and need to happen at 3 4 and 5 second intervals.
The behavior of these timers would not be adequate for this application because the following would happen:
The clock would stop rendering during the execution of the 'alarms'
The alarms may run over one another and thus they would queue up but not happen when they were supposed to happen, because the UI thread is processing all messages synchronously.
you end up with an unresponsive UI that does not do what you want.
So to answer as best I can your actual question; there does not necessarily need to be a limit to the amount of timers, just the interval between when they will fire in conjunction with the consideration of the time it will take to process your event handler.
If you are using the timers to fire separate processing threads that are going to come back to the UI thread eventually and make changes, then no there does not feasibly need to be a limit until you run into the upper end of the performance of your target machine. That is to say at some point the amount of timers could be so large that you are calling more timer events and clogging the message queue to the point that the form rendering becomes affected.
So in short:
Negative effects:
Timers run in the UI thread so they are blocking
they can have unexpected behaviors if your interval is shorter than the amount of time it takes to process your event handler.
In practice the only time you should need to limit your usage of timers, like any component that the user does not control, is if they begin to affect the user experience.
I hope that reads a lot less 'ramble-y' than it felt when I was writing it.

Related

Listen or wait for a specific time without using timer

Is there a way to listen or wait for a specific time (e.g. 11:30 am) every day. The only way I know how is to set a timer that checks for the current time every 60 seconds which I have actually implemented using a backgroundworker. But is there a way to just wait and listen for the specified time (similar to monitoring for directory changes) and then take some action?
Thanks in advance.
Typically, rather than having a program resident in memory waiting, you would setup a Scheduled Task for this (or a cron job on linux). The scheduled task will run the program at the appropriate time. The program can still check (validate) the expected time if needed, but it shouldn't just always sit in the background using up resources if it's only going to run once per day.
The scheduled task is also better because it will recover automatically from computer reboots, crashes, etc. If something happens that interrupts your program's normal running, the scheduled task will still be able to run.
This is especially important in the .Net world, because .Net requires you to be very careful writing long-lived programs to avoid address space fragmentation. The .Net garbage collector is good at freeing up and returning old memory to the operating system, but over time your program's virtual address space can become fragmented and eventually you will not be able to allocate new memory any longer.
Even if this is part of a larger program, where there are also other things happening based on user interactions, it's still a good idea to split this off into a separate process.

How to create a distributed 'debounce' task to drain a Redis List?

I have the following usecase: multiple clients push to a shared Redis List. A separate worker process should drain this list (process and delete). Wait/multi-exec is in place to make sure, this goes smoothly.
For performance reasons I don't want to call the 'drain'-process right away, but after x milliseconds, starting from the moment the first client pushes to the (then empty) list.
This is akin to a distributed underscore/lodash debounce function, for which the timer starts to run the moment the first item comes in (i.e.: 'leading' instead of 'trailing')
I'm looking for the best way to do this reliably in a fault tolerant way.
Currently I'm leaning to the following method:
Use Redis Set with the NX and px method. This allows:
to only set a value (a mutex) to a dedicated keyspace, if it doesn't yet exist. This is what the nx argument is used for
expires the key after x milliseconds. This is what the px argument is used for
This command returns 1 if the value could be set, meaning no value did previously exist. It returns 0 otherwise. A 1 means the current client is the first client to run the process since the Redis List was drained. Therefore,
this client puts a job on a distributed queue which is scheduled to run in x milliseconds.
After x milliseconds, the worker to receive the job starts the process of draining the list.
This works on paper, but feels a bit complicated. Any other ways to make this work in a distributed fault-tolerant way?
Btw: Redis and a distributed queue are already in place so I don't consider it an extra burden to use it for this issue.
Sorry for that, but normal response would require a bunch of text/theory. Because your good question you've already written a good answer :)
First of all we should define the terms. The 'debounce' in terms of underscore/lodash should be learned under the David Corbacho’s article explanation:
Debounce: Think of it as "grouping multiple events in one". Imagine that you go home, enter in the elevator, doors are closing... and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on... probably delaying the departure several minutes.
Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy you are polite enough to let people in for 10 secs, but once that delay passes, you must go!
Your are asking about debounce sinse first element would be pushed to list:
So that, by analogy with the elevator. Elevator should go up after 10 minutes after the lift came first person. It does not matter how many people crammed into the elevator more.
In case of distributed fault-tolerant system this should be viewed as a set of requirements:
Processing of the new list must begin within X time, after inserting the first element (ie the creation of the list).
The worker crash should not break anything.
Dead lock free.
The first requirement must be fulfilled regardless of the number of workers - be it 1 or N.
I.e. you should know (in distributed way) - group of workers have to wait, or you can start the list processing. As soon as we utter the phrase "distributed" and "fault-tolerant". These concepts always lead with they friends:
Atomicity (eg by blocking)
Reservation
In practice
In practice, i am afraid that your system needs to be a little bit more complicated (maybe you just do not have written, and you already have it).
Your method:
Pessimistic locking with mutex via SET NX PX. NX is a guarantee that only one process at a time doing the work (atomicity). The PX ensures that if something happens with this process the lock is released by the Redis (one part of fault-tolerant about dead locking).
All workers try to catch one mutex (per list key), so just one be happy and would process list after X time. This process can update TTL of mutex (if need more time as originally wanted). If process would crash - the mutex would be unlocked after TTL and be grabbed with other worker.
My suggestion
The fault-tolerant reliable queue processing in Redis built around RPOPLPUSH:
RPOPLPUSH item from processing to special list (per worker per list).
Process item
Remove item from special list
Requirements
So, if worker would crashed we always can return broken message from special list to main list. And Redis guarantees atomicity of RPOPLPUSH/RPOP. That is, there is only a problem group of workers to wait a while.
And then two options. First - if have much of clients and lesser workers use locking on side of worker. So try to lock mutex in worker and if success - start processing.
And vice versa. Use SET NX PX each time you execute LPUSH/RPUSH (to have "wait N time before pop from me" solution if you have many workers and some push clients). So push is:
SET myListLock 1 PX 10000 NX
LPUSH myList value
And each worker just check if myListLock exists we should wait not at least key TTL before set processing mutex and start to drain.

Can a WinRT background task be long-lived if within CPU and Network limits?

Microsoft's documentation states:
Background tasks are meant to be short-lived tasks that do not consume a lot of resources.
It also says:
Each app on the lock screen receives 2 seconds of CPU time every 15 minutes, which can be used by all of the background tasks of the app. At the end of 15 minutes, each app on the lock screen receives another 2 seconds of CPU time for use by its background tasks.
I need to run a background task every two minutes to update my live-tile.
My app is a lock-screen-app.
Computation is within the CPU and network usage constraints
Can I create a permanent background task (e.g. something which polls a web service and pulls information, waits and loops) to create a OneShot TimeTrigger every two minutes or is there a better way of doing this?
My concern with the background task option is whether the runtime would deem the task inactive while it was sleeping and close it or something else like there's a limit on the number of times a live tile can be updated within 15 minutes...
Yes, if by long lived you mean under 25 minutes.
Time triggers cannot execute more frequent than 15 minutes. Creating a OneShot trigger that executes in 2 minutes is, that's an interesting idea and should work. Yes, background tasks can register other background tasks to keep this chain going. Should the user's machine be off when it execs it will queue later.
Having said that, updating your tile that frequently & using a background task is not a wise solution. Because, it is unreliable. Background tasks can be disabled, for one. But every 15 minutes, you are going to exceed your quota. Try using a Scheduled tile instead.

How to fix major lag in NSTimers?

In a fairly simple application that I am making, I use many NSTimers, one which runs at a rate of .01 seconds that I use to change the position of multiple images. This causes major lag. How can I fix this? Please explain in detail, as I am fairly new to app dev.
From the NSTimer Docs (emphasis: mine):
A timer is not a real-time mechanism; it fires only when one of the
run loop modes to which the timer has been added is running and able
to check if the timer’s firing time has passed. Because of the various
input sources a typical run loop manages, the effective resolution of
the time interval for a timer is limited to on the order of 50-100
milliseconds. If a timer’s firing time occurs during a long callout or
while the run loop is in a mode that is not monitoring the timer, the
timer does not fire until the next time the run loop checks the timer.
Therefore, the actual time at which the timer fires potentially can be
a significant period of time after the scheduled firing time.
If you want to work at the display frequency, see CADisplayLink.
However, you should first understand where you program spends its time now to understand what makes it slow (profiler).

How many active objects can one ActiveScheduler handle?

I have a question about Symbian active objects handling. What's the problem: my program runs in 1 thread and have pretty much active objects in it. As per my logs, I see strange pauses in tasks processing. My program have about 30 simultaneously active objects in one ActiveScheduler. Is it okay?
Any Symbian Active Scheduler can handle pretty much as many Active Objects as you need.
Obviously, each added active object has a tiny performance impact on the whole scheduler but 30 is well within acceptable range.
You do have to remember this is all based on cooperative multitasking, though. If too many requests get completed too fast and active objects take too long to run, the time it takes for the scheduler to call RunL() on a specific single active object can become unacceptable for your application.