C# - scheduling a task to run every X minutes - c#

I am using a TaskFactory to manage my program's tasks. I would like to add a task to the queue that will start running after X minutes. Can it be done using .Net's standard tools or do I need to use a custom library for that.
Thanks

Yes this can be quite easily achieved. Look into some articles of basic multi-threading to ensure your UI is still responsive when scheduling/running these tasks. As has already been mentioned - the Timer control will do the trick.
The Programmers Heaven EBook on C#'s multi-threading section has enough in it to do what you want with regards to the multi-threading.

If you objective is to run something after a while you could use the Timer
Start the Timer, when the timer has elapsed, stop the Timer.

You could create a single-shot Timer that creates your Task when it fires. This means you won't be blocking a thread while you are waiting.
If you are writing a scheduler, you might want to look at Quartz.NET

Related

Pausing and resuming BackgroundWorker

I've been wondering is there any way in which we can move BackgroundWorker to sleep and resume it again just like thread. I've searched in many forums in vain. None of them show any method which would do that. I checked Microsoft documentation and found out there isn't any predefined methods.
I know the workarounds by using resetEvents. Just asking for any other possible and much easier way.
If you use Task instead of BackgroundWorker you can use the PauseTokenSource.
This class is similar to the built in CancellationTokenSource only suitable for pausing tasks and not canceling them.
PauseTokenSource API was built exactly for what you need and it's API can replace your usage of Thread.Sleep and all the signaling events.
Other option besides PauseTokenSource can use AsyncManualResetEvent, the mechanism internal is quite similar but they differ in the API. I think that PauseTokenSource is much more convenient and especially built for this purpose, more info here.
From within your DoWork handler, you can call Thread.Sleep() whenever you want. If you want, from the GUI, to be able to signal the worker to pause, set up a concurrent queue, feed your sleep requests into it from the GUI thread, and have your DoWork handler check the queue periodically, pausing as requested.
(If you want to pause the BackgroundWorker until signaled again rather than for a certain period of time, you can do that in a similar way--just periodically check the queue for a "restart" command and sleep a few milliseconds before checking again.)

Event vs. while(true) loop

Background is the following: A Windows Service which is supposed to perform an action once per day at a given time.
I have currently implemented this by creating a timer and added the ElapsedEventHandler. The event fires every t minutes and it is then checked that we are passed the configured time. If so the action is performed and if not nothing happens.
A colleague asked me if it was not easier just to have a while(true) loop containing a sleep() and then of course the same logic for checking if we are past the time for action.
Question:
Can one say anything about the "robustness" of an event vs. a while(loop)? I am thinking of the situation where the thread "dies" so the while(true) loop exits. Is this more "likely" to happen in the one scenario vs. the other?
I'd vote for neither.
If your service just sits idle for an entire day periodically waking up (and paging code in) to see if "it's time to run", then this is a task better suited for the Windows Task Scheduler. You can programatically install a task to run every day through the task scheduler. Then your code doesn't need to be running at all unless it's time to run. (Or if your service does need to run in the background anyway, the task in the scheduler can signal your service to wake up instead of timer logic).
Both will be equally robust if you use proper error handling.
If you don't use proper error handling they will be equally brittle.
while(true)
{
...
Thread.Sleep(1000);
}
will make your service slow when responding to the standard service events like OnStop.
Besides, where do you put your while loop? In a separate thread? You will get more manual management if you use a loop too.
To summarize: use a timer.

simpler C# code to introduce 1 mSec delay?

I am not using Thread so can't use thread.sleep() method.. Its part of my program where I need to introduce some delay .. Not precisely 1mSec but almost that ..
which is the standard method that is known to be so??
You are always using a thread. Every application has at least one thread, so Thread.Sleep will work fine.
I am not using Thread so can't use thread.sleep() method
Not sure you you say that -- you can use Thread.Sleep anywhere you like.
Just so you know, a 1msec sleep isn't guaranteed be exactly 1msec, in fact it's very improbable due to it being such a small time. The thread.sleep(x) states x as a minimum sleep time, if you wan't a much more exact sleep you might want to look into win32 multimedia timers: http://msdn.microsoft.com/en-us/library/dd742877.aspx
Don't sleep 1msec. It will not be accurate at all. Read for instance this article or this
Thread.sleep will always suspend the current thread. Keep in mind that it's not a good idea to use Sleep on a GUI thread (if your app is a winform app).
If you are just trying to provide an opportunity for thread switching, then use Thread.Sleep(0). (This is equivalent to Thread.Yield() in Java.)
Edit: actually seems like they've added Thread.Yield() in .NET 4.

what is the best approach for implementing a thread timer

What is the best approach in using a timer. Use a System.Timer.Timer class or use a single Thread in a non-terminating loop with a Thread.Sleep statement?
Thanks in advance
In general, use the components that are already there if they serve your needs. However, System.Threading.Timer uses the .NET thread pool, so any of the following conditions would make it a poor candidate:
You require a STA thread (all ThreadPool threads are MTA)
You require that all occurrences of your repeated task run on the same thread
You want to assign a particular priority (lower or higher) to your tasks
Your tasks are particularly long-running or utilize non-trivial blocks
Use a Timer. It's there, specifically for that purpose, so why wouldn't you use it?
The two methods you refer to are used for different results.
Timers will fire the event and invoke your method on a scheduled interval. They could invoke your method whilst another instance of it is running unless you stop the timer at the start of your processing (DoWork) and start it again when you're done (but then you might miss the timed events).
A method that loops and sleeps will not be invoked when it's busy. The "advantage" here is that you can DoWork, then find that the next timer event has already passed and DoWork immediately again. The alternative is that you have rest periods where you sleep a specified amount of time regardless of how long your DoWork method took.

C# Multi-Threading - What method to use?

My goal is to write a program that handles an arbitrary number of tasks based on given user input.
Let's say the # of tasks are 1000 in this case.
Now, I'd like to be able to have a dynamic number of threads that are spawned and start handling the tasks one by one.
I would assume I need to use a "synchronous" method, as opposed to a "asynchronous" one, so that in case one tasks has a problem, I wouldn't want it to slow down the completion of the rest.
What method would I use to accomplish the above? Semaphores? ThreadPools? And how do I make sure that a thread does not try to start a task that is already being handled by another thread? Would a "lock" handle this?
Code examples and/or links to sites that will point me in the right direction will be appreciated.
edit: The problem with the MSDN Fibonacci example is that the waitall method can only handle up to 64 waits. I need more than that due to the 1000 tasks. How to fix that situation without creating deadlocks?
Are these tasks independent? If so, you basically want a producer/consumer queue or a custom threadpool, which are effectively different views on the same thing. You need to be able to place tasks in a queue, and have multiple threads be able to read from that queue.
I have a custom threadpool in MiscUtil or there's a simple (nongeneric due to age) producer/consumer queue in my threading tutorial (about half way down this page).
If these tasks are reasonably long-running, I wouldn't use the system threadpool for this - it will spawn more threads than you probably want. If you're using .NET 4.0 beta 1 you could use Parallel Extensions though.
I'm not quite sure about your comment on WaitAll... are you trying to work out when everything's finished? In the producer/consumer queue case, that would probably involve having some sort of "stop" entry in the queue (e.g. null references which the consuming threads would understand to mean "quit") and then add a "WaitUntilEmpty" method (which should be fairly easy to implement). Note that you wouldn't need to wait until the last items had been processed, as they'd all be stop signals... by the time the queue has emptied, all the real work items will definitely have been processed anyway.
You'll probably want to use the ThreadPool to manage this.
I recommend reading up on MSDN on How to use the ThreadPool in C#. It covers many aspects of this, including firing tasks, and simple synchronization.
Using Threading in C# is the main section, and will cover other options.
If you happen to be using VS 2010 beta, and targetting .NET 4, the Task Parallel Library is a very good option for this - it simplifies some of these patterns.
You can't use it (yet) but the new Task class in .NET 4 would be ideal for this kind of situation.
Until then, the ThreadPool is your best bet. It has a (very) limited form of load-balancing. Note that if you try to start 1000 Threads you will probably get an Out Of Memory exception. The ThreadPool will handle that with ease.
Your sync problem can be handled with a simple (Interlocked) counter, if the timing is such that you can tolerate a Sleep(1) loop in the main thread. The ThreadPool is missing a more convenient way to do this.
A simple strategy to avoid a task is get by two or more thread is a syncronized (with a mutext for example) vector.
See this http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx
Perhaps you can use the BackgroundWorker class. It creates a nice abstraction on top of the thread pool. You can even subclass it if you want to setup many similar jobs.
As has been mentioned, .NET 4 features the excellent Task Parallel Library. But you can use the June 2008 CTP of it in .NET 3.5 just fine. I've been doing this for some hobby projects myself, but if this is a commercial project, you should check out if there are legal issues.

Categories