I'm developing a c# winform application which is based on third party web API's for trading purpose. It deals with real time data coming from internet like currency rates but I'm using 8 timer in my winform to retrieve different data, application gets non-responding because of timers,
what can i do to make this application work fast and smooth?
You might want to look into the System.Threading.Timer instead:
Timer Class
System.Threading.Timer, which executes a single callback method on a
thread pool thread at regular intervals. The callback method is
defined when the timer is instantiated and cannot be changed. Like the
System.Timers.Timer class, this class is intended for use as a
server-based or service component in a multithreaded environment; it
has no user interface and is not visible at runtime.
This link has a nice table of comparison between the different timer classes at the bottom:
Comparing the Timer Classes in the .NET Framework Class Library
Use threading. Timers (at least the ones you seem to be using) are executed in the GUI's thread. Use BackgroundWorkers (or other threading methods) instead to decouple background tasks from the GUI.
Related
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 read this excellent article Comparing the Timer Classes in the .NET Framework Class Library and came to the conclusion that anything I could do with Windows.Forms.Timer I can do better with Timers.Timer - and then some.
So the obvious question that comes to mind is: Why is the Windows.Forms Timer offered at all?
Legacy (backward compatibility) support?
Other?
The main convenience of the Windows.Forms.Timer is that its events are fired on the UI (Winforms) thread. If your timer events perform UI operations, it may be the simplest alternative (instead of calling Control.Invoke/BeginInvoke or SynchronizationContext.Post/Send inside all of your events).
The Windows.Forms.Timer events get invoked on the UI thread so you can update the UI from the event handlers directly, which is not normally the case with Timers.Timer (as you would get cross thread access violation exceptions).
And, as #Robert Harvey answered, it also has designer support.
One of advantage of Windows.Forms is that it run in the same thread of GUI and you do not get cross thread exceptions while accessing Form controls.
Windows.Forms.Timer has designer support. So it behaves like any other Winforms component (i.e. you can drag it onto a form, it's part of the Controls collection, etc).
Timer events raised by System.Windows.Forms.Timer class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class (assuming you don't call Application.DoEvents). Events fired by the Windows.Forms.Timer class are compatible with your Winform controls; you can safely interact with them without having to call Invoke().
The System.Timers.Timer class is a server-based timer that was designed and optimized for use in multithreaded environments. Instances of this timer class can be safely accessed from multiple threads. Although Invoke() is technically required to interact with Winforms, the Timer class does provide a SynchronizingObject property, to which you can attach the Windows form with which you want to safely interact.
More here:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Well I think the answer is that they are two completely different types of timers. The Windows.Forms.Timer is a single-threaded application timer that's well suited for timers existing on the client running application.
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.
In contrast the Timers.Timer is a server-based timer that is better suited for Windows services.
The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.
You can find their documentation and read the excerpts and more from Microsoft.
It's not that one should never be used or always used, the serve two different purposes.
My belief is that it is for winform designer integration, in that you can drag it onto a form, click it and set its properties in the properties pane.
I've got a few instances of the same class. During the classes lifetime, every method call on this class should be executed on the same thread. But for each instance I need a different thread.
I thought about Threadpool, but it seems that I have too less control about it.
How can I reuse a thread without using ThredPool?
Thank you! Martin
Edit (why I need this):
I have to use a win32 dll to access business logic of a third-party product. This dll is not designed for a multi-threaded environment like a web application. When I run my ASP.NET MVC application in ASP Classic Mode (STA Thread), everything works fine so far. But the problem is that all users going to block each other. This component also maintains some state. As soon as a different thread is accessing this component, it will not recognize the connection-handle I have to pass in for each method call. I got the connection handle after a logon procedure. I want to put my web application in MTA mode back again and use a worker-concept, assigning about 10 users to a worker (max. 10 users should block each other). One worker should always use the same thread to execute the api calls so the component will not stubmle.
I'm not happy with this situation, but I have to find am acceptable solution.
Update - Found a Solution:
Thanks to the "Smart Thread Pool" from Ami Bar I could accomplish the behavior I was looking for (easily). For each worker, I have now my own thread pool instance with a max and min number of one thread. Well, it's not the idea of a thread pool, but it makes it very easy to handle the work-items and it also has some nice other featrues. The web application is running on MTA now.
I'm going to prepare some load tests to see if its stable over hours.
see here: http://www.codeproject.com/Articles/7933/Smart-Thread-Pool
I have built a component library that includes an executive class which does work on any number of threads and fires events from these threads. This is all good. Now I want to use my executive in a desktop app. (Winforms in the first instance, WPF later on) so I want to marshall all event calls back onto the UI thread. I know of a 3 ways to do this;
Check IsInvokedRequired/call Invoke in the handlers; This is lame IMO.
Create a decorator for the executive that uses the event base async model; Gives me the desired result, not very exciting though.
Use the WPF dispatcher; feels wrong to use a WPF class in Winforms app. or even more wrong to use it in the component lib.
I have spent the last hour or so reading up on Rx and I'm thinking the ideal solution might be to bake Rx into the executive and have the executive take (optionaly) a scheduler. This way the client of the executive can determine the behaviour with regard to the which thread/s the events are raised on and I get all of the other Rx goodness. Or perhaps create an RxExecutive that takes a Scheduler and encapsulates my existing executive to provide an Rx API.
Am I thinking along the right lines or have I missed the point?
Rx does provide a very nice way to access the UI thread in a Windows Forms app. You can use the full Rx library of observables, but if you just need an easy way to run things on the UI thread then using the ControlScheduler is a snap.
Assuming you have a form called form1 just do this:
var scheduler = new System.Reactive.Concurrency.ControlScheduler(form1);
scheduler.Schedule(() => { /* Do Stuff on UI thread */ });
Easy.
You don't have to use a reference to the form - you could use any control.
I believe the preferred pattern is to specify the scheduling SynchronizationContext. SynchronizationContexts are available for both WPF and WinForms applications, are used to schedule WF4 and WCF, and I'm sure are also used in other parts of the framework.
You are on the right track. Alternatively, you could have the users that care about the thread use ObserveOn. The advantage of this is that only the observer code is run on the needed thread.
I am trying to port some code from C++ to C#.
I came across this in the C++ code:
watchdogTimer = SetTimer(1,1000,NULL);
...
KillTimer(watchdogTimer);
What is this code doing, and how can this be ported to C#?
Thanks.
The CWnd::SetTimer function you're looking at creates a timer that sends WM_TIMER events to the window. This is analogous to the System.Windows.Forms.Timer component in .NET. It behaves somewhat differently than the System.Timers.Timer. There are two differences that are particularly relevant:
Windows.Forms.Timer calls the event handler on the UI thread. By default, System.Timers.Timer calls the event handler on a threadpool thread. You can use SynchronizingObject property to have the System.Timers.Timer call on the UI thread.
Another difference is that it's not possible to encounter reentrancy problems with the Windows Forms timer because Windows won't allow multiple WM_TIMER messages from the same timer in the queue, nor will it place a WM_TIMER message in the queue if one is already being processed. This is generally a good thing.
System.Timers.Timer, on the other hand, will allow reentrancy. So if your timer event handler takes longer than the timer period, you can be processing multiple events for the same timer concurrently. If your timer period is 100 ms and processing takes 150 ms, you're going to get another notification while you're processing the first one. If you use the SynchronizingObject to force the callback on the UI thread, this can lead to a whole bunch of pending callbacks being queued.
The implementation of the two timers is quite different. The Windows Forms timer uses old style Windows timers that have been around for 20 years. This type of timer requires a window handle and a message loop, and is therefore used only in GUI programs. System.Timers.Timer is a thin wrapper around System.Threading.Timer, which uses the Windows Thread Pool Timers.
Assuming that your application is written under MFC, the SetTimer() method belongs to class CWnd and is responsible for setting up a windows timer. Documentation for this can be found at http://msdn.microsoft.com/en-us/library/49313fdf(v=vs.80).aspx. I know little about .NET but a quick google search located the following this: http://msdn.microsoft.com/en-us/library/0tcs6ww8(v=VS.90).aspx.