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.
Related
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.)
I'm building a rather simple application that performs a few seperate HTTPWebRequests, each on their own timer. It's not likely I will need to have more than 3 seperate requests running at a time.
If a Timer Tick fires while another HTTPWebRequest is in progress, what happens to the event fired by the Timer Tick? Should I add Threading?
The answer is almost always - no, don't use threads just because you can.
Consider making asynchronous calls first as it is easier to write correct code for. It is likely more efficient use of resources (as threads are not unlimited resource) if you need additional arguments.
Links:
How to use HttpWebRequest (.NET) asynchronously?
Use async methods of WebClient like WebClient.DownloadStringAsync
When Timer.Tick fires it's handler will be scheduled for execution in Thread Pool and most likely, executed in another thread.
I have created an array of threads and started all of them. How to know whether all threads have completed work. I don't want to use thread.wait or thread.join.
If you are using .NET 4 you could use the Task Parallel Library and the ContinueWhenAll method.
You'd have to modify your threads to be represented as Task's. Tasks are easier to work with then threads. Usually you do not have to worry about lower-level things as you are forced to do now like scheduling or waiting for things to complete.
Well, you can test Thread.IsAlive - but that will be out of date as soon as you've tested it, of course. You could keep a list of "currently alive" threads, and remove them one at a time when they stop, sleeping between test runs. For more detailed information you can use Thread.ThreadState.
What's the bigger picture here? What are you trying to achieve, and why don't you want to call Thread.Join (potentially with a timeout)?
What about MyThread.ThreadState == System.Threading.ThreadState.Stopped ?
Have the threads call back to the class that you started them in to signal that they are done
You could use the ThreadPool class instead of an array, and use the 'GetAvailableThreads' method to check if all threads are available. See:
ThreadPool class.
if you want to intercept the work asynchronously you can use BackgroundWorkers all of which have a RunWorkerCompleted event and a Error and Cancelled properties in the event args
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
I am using asynchronous methods in some of my project and I like it since it allows my application to be a lot more scalable. However, I am wondering how asynchronous methods really work in background? How .NET (or Windows?) knows that a call is completed? Depending on the number of asynchronous calls I made, I can see that new threads are created (not always though…). Why?
In addition, I would like to monitor how long a request take to complete. To test the concept, I wrote the following code which calls asynchronously a Web service and immediately after starts a stopwatch.
for (int i = 0; i < 10000; i++)
{
myWebService.BeginMyMethod(new MyRequest(), result, new AsyncCallback(callback), i);
stopWatches[i].Start();
}
// Call back stop the stopwatch after calling EndMyMethod
This doesn’t work since all the requests (10000) have the same begin time and the duration will go up linearly (call 0 = duration 1, call 1 = duration 2, etc.). How could I monitor the real duration of a call with asynchronous method (from the moment the request is really executed until the end)?
UPDATE: Does an asynchronous method block the flow? I understand that it uses the .NET ThreadPool but how an IAsyncResult know that a call is completed and it's time to call the CallBack method?
The code is the railroad and the thread is the train. As train goes on railroad it executes the code.
BeginMyMethod is executed by the main thread. If you look inside the BeginMyMethod it simply adds a delegate of MyMethod to the ThreadPool's queue. The actual MyMethod is executed by one of the trains of the train pool. The completion routine that is called when MyMethod is done is executed by the same thread that executed the MyMethod, not by your main thread that runs the rest of the code. While a thread pool thread is busy executing MyMethod, the main thread can either ride some other portion of the railroad system (execute some other code), or simply sleep, waiting until certain semaphore is lit up.
Therefore there's no such thing as IAsyncResult "knowing" when to call the completion routine, instead, completion routine is simply a delegate called by the thread pool's thread right after it's done executing MyMethod.
I hope you don't mind the somewhat childish train analogy, I know it helped me more than once when explaining multithreading to people.
The crux of it is that calling Begin queues up a request to execute your method. The method is actually executed on the ThreadPool, which is a set of worker threads provided by the runtime.
The threadpool is a fixed set of threads to crunch through async tasks as they get put into the queue. That explains why you see the execution time take longer and longer - your methods may each execute in approximately the same time, but they don't start until all previous methods in the queue have been executed.
To monitor the length of time it takes to actually execute the async method, you have to start and stop the timer at the beginning and end of your method.
Here's the docs for the ThreadPool class, and an article about async methods that do a better job of explaining what's going on.
Asynchronous methods work by using the .NET ThreadPool. They will push the work onto a ThreadPool thread (potentially creating one if needed, but usually just reusing one) in order to work in the background.
In your case, you can do what you're doing, however, realize that the ThreadPool has a limited number of threads with which it will work. You're going to spawn your work onto background threads, and the first will run immediately, but after a while, they will queue up, and not work until "tasks" run before completely. This will give the appearance of the threads taking longer and longer.
However, your stopwatch criteria is somewhat flawed. You should measure the total time it takes to complete N tasks, not N times to complete one task. This will be a much more useful metric.
Its possible that a majority of the execution time happens before BeginMyMethod(). In that case your measurement will be too low. In fact, depending on the API, BeginMyMethod() may call the callback before leaving the stack itself. Moving up the call to StopWatch.Start() should help then.
I want to implement a timeout on the execution of tasks in a project that uses the CCR. Basically when I post an item to a Port or enqueue a Task to a DispatcherQueue I want to be able to abort the task or the thread that its running on if it takes longer than some configured time. How can I do this?
Can you confirm what you are asking? Are you running a long-lived task in the Dispatcher? Killing the thread would break the CCR model, so you need to be able to signal to the thread to finish its work and yield. Assuming it's a loop that is not finishing quick enough, you might choose to enqueue a timer:
var resultTimeoutPort = new Port<DateTime>();
dispatcherQueue.EnqueueTimer(TimeSpan.FromSeconds(RESULT_TIMEOUT),
resultTimeoutPort);
and ensure the blocking thread has available a reference to resultTimeoutPort. In the blocking loop, one of the exit conditions might be:
do
{
//foomungus amount of work
}while(resultTimeoutPort.Test()==null&&
someOtherCondition)
Please post more info if I'm barking up the wrong tree.
You could register the thread (Thread.CurrentThread) at the beginning of your CCR "Receive" handler (or in a method that calls your method via a delegate). Then you can do your periodic check and abort if necessary basically the same way you would have done it if you created the thread manually. The catch is that if you use your own Microsoft.Ccr.Core.Dispatcher with a fixed number of threads, I don't think there is a way to get those threads back once you abort them (based on my testing). So, if your dispatcher has 5 threads, you'll only be able to abort 5 times before posting will no longer work regardless of what tasks have been registered. However, if you construct a DispatcherQueue using the CLR thread pool, any CCR threads you abort will be replaced automatically and you won't have that problem. From what I've seen, although the CCR dispatcher is recommended, I think using the CLR thread pool is the way to go in this situation.