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.
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 want to execute the certain method of a class in regular interval when certain method is executed. C# has three methods I can use to furnish my needs. Since I am new to C# programming, I am confused in selecting the right method. Based on my study, the three classes are:
System.Windows.Forms.Timer
Systems.Timer
System.Diagnostics.StopWatch
My requirement is fairly simple: Execute the certain method at regular interval when the certain method is called.
Please suggest the situation where one is more preferred over others.
StopWatch is for measuring time, not for scheduling events, so let's rule that one out.
System.Windows.Forms.Timer is based on Windows Forms and requires the Windows message loop to run. Is your project Windows Forms, then you can use this. If not, do not use it (it won't work).
System.Timers.Timer is a general purpose timer. I would use this; it should work in all scenarios, you don't have to worry about the message loop running. You can also make this Timer synchronize automatically using it's SynchronizationObject property.
Finally, there is a System.Threading.Timer, which is not thread safe out of the box (meaning your method will get called on a worker thread, so if you need synchronization or dispatch on a specific thread due to UI, you will need to handle that yourself).
There are many subtle differences to these timers, I'd recommend you read the article Comparing the Timer Classes on MSDN for the full story.
Without knowing your specific use case, we can't tell you which is best. But in general:
System.Windows.Forms.Timer - Will call your function on the UI thread each time. Use this if you are planning to access UI controls during the event.
System.Timers.Timer - Will call your function on a worker thread. Use this in a context that is not Windows Forms or where you don't need to access any UI elements
System.Diagnostics.StopWatch - this is for timing how long things take. It won't help you here.
See: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
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
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.
I have a problem with interface lag in C#.
Since I'm still learning please be patient whilst I explain.
I have narrowed the problem to my timer object.
Basically my program queries a device through TCP/IP socket and outputs it to a textbox on screen.
Now I am polling the device for data every second which requires some logic to be buried within timer object and the following is what happens between ticks:
Increment a value.
Construct the 2 strings that represents the command to be sent to
the box (encapsulated in a function
Encode the command
Send command
Clear the byte array
Receive reply.
Could this be too much processing being done in the event handler? Every time I try to move the window during the polling session i.e. when the timer is running I get a very bad input lag.
The timer you are using is executing on the windows message thread. Therefore, while the polling is running the windows message queue is blocked. This isn't a problem with doing too much processing, most of the time the thread will be waiting for the TCP/IP response.
To fix this, you just have to do the do the work on a background thread and then update the UI on the UI thread.
There are a heap of different timers in the .NET framework that work in different ways, the one you are using works processed the timer event on the same thread, others work on background threads. Check this article out about the different timers.
You could also just use your current timer to invoke a BackgroundWorker component to do the work on the background thread. The main benefit of this is the the BackgroundWorker will do the work on a background thread, but will raise the work complete event on the UI thread so that it is simple to update the UI without having to worry about which thread you are on.
I think this is because you're trying to do work in your UI thread. Have your timer run in a background work thread.
It seems like there are a few things going on. First, you may be doing too much in your timer tick handler. How are you constructing the string and encoding the command? Can any of this be done once outside the tick handler or simplified in any way (using String.Format calls, for instance)? There are actually three different timers available in .NET, with different resolutions. Which timer are you using?
The biggest issue is the fact that your interval is 1 second. No matter what, that is a lot of processing overhead. Keep in mind that, for the most part, every time the interval is hit and the tick handler is invoked you are causing a context switch between threads. There is a bit of overhead involved in this (nothing which you can do anything about) and the more often you context switch the slower your performance appears.