Franapoli wrote: | |
Sorry, I meant this one.
But searching again for it, i also found this one and now I'm a bit confused... how do I choose beetween system.timers and system.threading.timers
Thank you.
|
|
MSDN briefly notes on the difference between the two:
System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.
Both can be used with static an non-static callback functions. In the latter case, you must of course make sure that the function is called on an instance of a class.
Modifying the example from System.Timers.Timer, to work on a non-static function, can be done such as:
// cli.cpp : main project file.
#using <system.dll>
using namespace System; using namespace System::Timers;
public ref class Timer1 { public: void Demo() { // Normally, the timer is declared at the class level, so // that it doesn't go out of scope when the method ends. // In this example, the timer is needed only while Demo // is executing. However, KeepAlive must be used at the // end of Demo, to prevent the JIT compiler from allowing // aggressive garbage collection to occur before Demo // ends. System::Timers::Timer^ aTimer = gcnew System::Timers::Timer;
// Originally: aTimer->Elapsed += gcnew ElapsedEventHandler( Timer1::OnTimedEvent ); // Changed to work on a non-static member function, given an instance pointer "this" // for the callback to be run on the current object. aTimer->Elapsed += gcnew ElapsedEventHandler( this, &Timer1::OnTimedEvent );
// Set the Interval to 2 seconds (2000 milliseconds). aTimer->Interval = 2000; aTimer->Enabled = true;
Console::WriteLine("Press the Enter key to exit the program."); Console::ReadLine();
// Keep the timer alive until the end of the Demo method. GC::KeepAlive(aTimer); }
private: // Specify what you want to happen when the Elapsed event is // raised. void OnTimedEvent( Object^ /*source*/, ElapsedEventArgs^ /*e*/ ) { Console::WriteLine( "Hello World!" ); }
};
int main() { Timer1 t; t.Demo(); }
|