time or timing in C#, and another question - c#

the question is:
how can i for example every two seconds without user intervention make a label flashes.
like every 2 seconds label.text="". and the next two seconds i do this label1.text="visible"
or changing another property like color or anything.
i give up
could you help me with a basic code, thank you.

You may try using the timer with a 2-second interval. But keep in mind, whenever you play with threads outside of the UI, you need to look in to delegates and BeginInvoke
To accomplish what you're after, you could run it every 1 second, then check against DateTime.Now to see if the clock matches your criteria.

Your question is a bit difficult to understand, but I'll give it my best shot.
From what I understand, you want your code to do something every two seconds. The easiest way to do that is with a timer. The System.Timers.Timer class is useful for that, as well as System.Threading.Timer. Which you use is up to you, but the one in the Threading namespace is a little more primitive.
Timers operate on a ThreadPool, so if you will be manipulating a Windows Form, make sure what you do happens on the GUI thread either by using Control.Invoke for Windows Forms or Dispatcher.Invoke for WPF. Timers are also a little tricky because their Threading Apartment is typically MTA, so if you try to access the clipboard or something like that, you may get errors.
If you want to ensure your timer fires exactly at a certain time, rather than at a specific interval, you could make a timer with a period that starts another timer, or adjusts itself. I would argue that if you are doing something every 2 or 5 seconds do you really need it to happen at a very specific time? Timers, and Windows Time in general isn't specific enough and has small inaccuracies - it will drift over time by a few milliseconds.

What you could do with one thread is something like this :
Sleep 2 seconds
DoAction
Sleep 2 seconds
DoAnotherAction
In a loop.
With 2 threads, I would recommend something like this : C# Running timed job on StackOverflow
Edit : use QuartzNet (tutorial).
A link on StackOverFlow.

The easiest way to do this is with System.Windows.Forms.Timer. You can drop it on your form and set the interval, and create the Tick event handler. The linked documentation has a simple example that you can easily modify to work with your label.
The beauty of using this timer is that it automatically synchronizes with the UI thread, so you don't have to worry about Invoke, BeginInvoke, etc.

Related

Is there a feature in matlab like background worker?

I need something like background worker in C# to use in matlab. fyi drawnow will not be useful because I don't want the background thread in GUI. I need it in processing.
so, Is there something like that in matlab?
thanks.
No. Not really. Matlab is almost entirely a single threaded environment.
There are a few caveats associated with that.
Some aspects of worked threads can be accomplished by a clever use of Timer objects. One item is executing at a a time, either a timer object or the main execution activity. Timers will not interrupt each other, but they can interrupt the main execution thread. So you could put the expensive operation in the main activity and some maintenance activities in timers.
Determining what functions can be interrupted by Timers is tricky. My best effort to figure it out is in this answer to another question. I've worked with Mathworks on this and determined there is really no satisfying answer.
Java methods can be executing from the event dispatch thread. See javaMethodEDT. (This probably doesn't help you, but I'm trying to optimize my Matlab/threading speech.)
External programs, (e.g. Java, C, C# etc) can bring their own threads. These programs can be run from Matlab.
I found something completely like the back ground worker in C# ..
t = timer('TimerFcn',#(x,y)disp(clock),'StartDelay',5,'ExecutionMode','fixedSpacing');
start(t)
The back ground thread will run after 5 seconds and displays the output of clock function.
'fixedSpacing' means that it will run automatically after it ends.

Performance for Timer vs DispatcherTimer

I don't have a specific scenario in mind, but this question just crossed my mind while I was thinking of scenarios where I may want to use a Timer over a DispatcherTimer.
In the scenario where I have to perform come computationally intensive task whenever a timer event fires, and then make minor modifications to UI, would it be better in terms of performance to:
use a regular Timer and then use the application's Dispatcher to
change the UI
use a DispatcherTimer (and possibly do my computationally
intensive work in some async background worker if necessary).
My guess is that keeping the UI thread unblocked for as long as possible will enhance the user experience. If this is advisable, Are there any catches that I should be aware of in such a scenario?
EDIT:
I get the feeling my question was not clear enough, so I'm going to try and add a concrete, albeit made-up example.
Let's say I have to read a large file every 2 minutes, and when I'm done, I have to add an item to a ListBox. Let's say reading/processing the file takes 10-15 seconds, during which I do no UI work. What would be the best approach for something like this?
Main point:
to perform come computationally intensive task
This would indicate not using the DispatcherTimer. It mainly exists to perform small tasks on the main thread and avoid creating another thread.
If you use a DispatcherTimer to start a Backgroundworker you're circumventing its main purpose.
So just use a regular Timer here.
After some more research and analysis, I've come to the conclusion that a regular timer works best in my made-up example. So far, I haven't had to look out for anything specific that would cause potential problems in my code. Having said that, good coding practices never hurt!
Timer generates recurring events in an application
DispatcherTimer is a timer that is integrated into the Dispatcher
queue which is processed at a specified interval of time and at a
specified priority.
Timers are not guaranteed to execute exactly when the time interval occurs, but are guaranteed not to execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes, it is dependent of the other jobs in the queue and their priorities.
If a Timer is used in a WPF application, it is worth noting that the Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set.
Comparing Timer with DispatcherTimer
Some answers posted here are more specific to your question but I think this link offers some general information and advice.
If you want to change a scalar (not a collection) value binded to UI element, you can do it not only from UI thread (e.g. from Timer delegate). And in this case you don't need to use Dispatcher.Invoke/BeginInvoke.
Another option is to use DispatcherTimer with creating BackgroundWorker class instance on each timer iteration. It also frees you from using Dispatcher.Invoke/BeginInvoke in many cases.

How to add actual wait?

Im currently trying to code very simple thing.
what it supposed to do:
enter google
wait 5 seconds
search something.
now, the part I cant do is wait.
There is thread sleep etc. but they stop GUI and makes my program unusable.
I can also do it with timers but it isnt very effective way to do it, since in actual app there will be many waits...
Are there anyway to do with it like 2-3 lines of code only, and without stopping GUI?
A timer is exactly what you want here - you want to say, "In 5 seconds, do X" (potentially executing in the UI thread) which is exactly what a timer does for you. If you want to encapsulate that in a single method which you can pass in an Action and a TimeSpan or whatever, that's fine - but a timer is definitely the way to go.
(The type of timer you want to use will depend on what thread you want the timer to fire on, etc.)
You need to do the work on a seprate thread so it dosent halt the GUI thread.
Thread worker = new Thread(dowork);
worker.Start();

Windows Service needs to wait, Thread.Sleep?

I have a c# windows service that needs to execute a database query every 60 seconds (or whatever interval is set in the config file). I'm using Thread.sleep(60) in a while loop to accomplish this. Is there a better way to do this?
Thanks
You can use a System.Threading.Timer to run your code every 60 seconds instead of doing it in a sleeping thread.
It depends on what you want to do. If you want a (more) exact method you may want to use System.Threading.Timer. One thing about thread.sleep is that it really is "sleepatleastuntil...". The processor will ignore your thread until the sleep time is past. The next time it would give your thread priority, after the sleep time is past, it will.
This will normally be very close to the desired interval, but could be longer. Don't yield unless you really intend to yield.
Use a Timer to fire the process every 60 seconds rather than force the process to sleep.

How scalable is System.Threading.Timer?

I'm writing an app that will need to make use of Timers, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread?
I guess another way to rephrase the question is: How is System.Threading.Timer implemented?
I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: http://www.codeplex.com/NetMassDownloader
Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it...
They definitely use pool threads rather than a thread-per-timer, though.
The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list.
Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers.
Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running.
I think you might want to rethink your design (that is, if you have control over the design yourself). If you're using so many timers that this is actually a concern for you, there's clearly some potential for consolidation there.
Here's a good article from MSDN Magazine from a few years ago that compares the three available timer classes, and gives some insight into their implementations:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Consolidate them. Create a timer
service and ask that for the timers.
It will only need to keep 1 active
timer (for the next due call)...
For this to be an improvement over just creating lots of Threading.Timer objects, you have to assume that it isn't exactly what Threading.Timer is already doing internally. I'd be interested to know how you came to that conclusion (I haven't disassembled the native bits of the framework, so you could well be right).
^^ as DannySmurf says : Consolidate them. Create a timer service and ask that for the timers. It will only need to keep 1 active timer (for the next due call) and a history of all the timer requests and recalculate this on AddTimer() / RemoveTimer().

Categories

Resources