开发过程中经常遇到定时触发的需求,如:TCP/IP连接中,使用心跳包保持连接或检测连接是否已经中断。
WPF中有多种定时器:
1.using System.Windows.Threading;
代码如下:
using System.Windows.Threading; public partial class MainWindow : Window
{
DispatcherTimer timerHeartBeat = new DispatcherTimer(); public MainWindow()
{
timerHeartBeat.Tick += SendHeartBeatToServer;
timerHeartBeat.Interval = TimeSpan.FromSeconds( * );
timerHeartBeat.Start();
} private void SendHeartBeatToServer(object sender,EventArgs e)
{
string strToSend = "{CMD:'99999'}";
SendMsg(strToSend);
}
}