C# (定时器、线程) Timer DispatcherTimer Thread
Timer
using System ;
using System. Threading ;
using System. Threading. Tasks ; private static Timer mTimer; mTimer = new Timer ( recvTimerCalback, null , 0 , 1 ) ; private void recvTimerCalback ( object obj)
{ Console. WriteLine ( "TickCount:" + Environment. TickCount) ; this . Dispatcher. Invoke ( new Action ( ( ) => { } ) ) ;
}
mTimer . Change ( 10 , 500 ) ;
DispatcherTimer
定时器被设置为1秒触发一次,并在第一次触发后停止。你可以在timer_Tick方法中添加你需要执行的代码。
using System ;
using System. Windows. Threading ;
DispatcherTimer timer = new DispatcherTimer ( ) ;
timer. Interval = TimeSpan. FromMilliseconds ( 1000 ) ;
timer. Tick += new EventHandler ( timer_Tick) ;
timer. Start ( ) ;
void timer_Tick ( object sender, EventArgs e)
{ ( sender as DispatcherTimer ) . Stop ( ) ;
}
Thread
using System ;
using System. Threading ;
using System. Threading. Tasks ; private Thread recvThread;
private void recvThreadTask ( )
{ Thread. Sleep ( 100 ) ; while ( true ) { }
} recvThread = new Thread ( recvThreadTask) ;
recvThread. Start ( ) ;
if ( recvThread != null )
{ recvThread. Abort ( ) ;
}