在使用WPF时需要一个定时器控制自动查询
查阅了很多方法后发现可以使用DispatcherTimer作为委托来更新窗口的主控件(说的不对请留言纠正)
private int iInterval = 10000;
private Timer aTimer = null;
private delegate void TimerDispatcherDelegate();
public MainWindow()
{
InitializeComponent();
oraConn = new OracleConnection(sConnectString);
oraConn.Open();
aTimer = new Timer(iInterval);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);// 直接调用方法可能出错 这里使用一个方法过度一下
aTimer.Interval = 500; // 定时器间隔时间(这里是打开前端界面后界面的刷新效果时间)
aTimer.Start();// 控制定时器开关 等同于 aTimer.Elapsed = true
}
private void OnTimedEvent(object sender, EventArgs e)
{this.Dispatcher.Invoke(DispatcherPriority.Normal, new TimerDispatcherDelegate(QryInfo));
}
private void QryInfo()
{
try
{string sLine = textLine.Text.Trim(); // 向方法中传递参数
QryData(sLine);
Debug.WriteLine(DateTime.Now.ToString() + " " + "修改成每隔" + iInterval.ToString() + "毫秒运行一次");
aTimer.Interval = iInterval;// 设定定时器时间
}
catch (Exception e)
{
throw e;
}
}
public void QryData(string sLine)
{
// 这里添加方法中需要执行的过程
}
借鉴文章:
https://www.cnblogs.com/zhchbin/archive/2012/03/06/2381693.html
https://www.cnblogs.com/wwwbdabc/p/11280667.html