I would like to call a method pass开发者_C百科ing a parameter every 20 seconds, e.g. public void ProcessPerson(IPerson person)
I’ve been reading through the different Timer options and was wondering if anybody could recommend the most efficient way to do this?
In addition, is there a way to keep the parameter strongly typed rather than use object and then have to convert to IPerson?
Thank you for your help.
A System.Threading.Timer
is what you need:
Provides a mechanism for executing a method at specified intervals.
Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.
There's also the System.Windows.Forms.Timer
:
Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.
This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing.
And don't forget System.Timers.Timer
:
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.
The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.
So investigate each and decide which one works best in your case.
I would go for System.Threading.Timer. Keep in mind that Windows is not a real-time OS system so there will be some variance on the timing no matter what mechanism you choose.
You did not say if this function will be performing any kind of UI updates, but just in case you should also know that the callback function will be executed on a different thread so in some cases like performing UI updates you will need to take the appropriate action to marshal the request back to the UI thread.
To marshal the request back to the UI thread you can do the following
For WinForms you can use Control.Invoke
For WPF you can use Dispatcher.Invoke
Or the Async variant BeginInvoke
You can use this, just make sure whatever you are doing is thread safe.
using System.Threading;
public void DoStuff(IPerson person)
{
new Timer(ProcessPerson, person, 0, 20000);
}
public void ProcessPerson(object threadState)
{
IPerson person = threadState as IPerson;
// do your stuff
}
精彩评论