首先Timer 是采用回调机制,所以要保证实力一直被引用着,不然就会被垃圾回收。
所以最好生命全局的Timer实例。
其次Timer 由于有2个时间参数,分别为Duetime和PeriodTime前者是首次延迟,后者是下次的间隔时间。
如果使用者在创建Timer实例时填入两个参数。最好在程序内部用Change()函数修改下时间。不然
由于Timer自身的机制,会有多次调用的现象。
----------------------------------------------------------------------参考代码------------------------------------------------------------ #region(菜单栏)
private void TMSI_Child_Run_Click(object sender, EventArgs e)
{
//服务器IP标识
_ServerName = this.Name.Replace("DBC-OMC-","").Trim();
strPickFilePath = AppDomain.CurrentDomain.BaseDirectory + "//" + DateTime.Now.ToString("yyyyMMdd") + "-" + _ServerName + strPickFilePath;
dspPickStatusTip(FRM_Task_BLL.UserTip.Run);
timerPick = new System.Threading.Timer(new TimerCallback(GetOMCDate), null, lDueTime, 0);
//程序已经运行即禁用运行设置
TMSI_Child_Run.Enabled = false;
//GetOMCDate(null);
}
private void TMSI_Child_Stop_Click(object sender, EventArgs e)
{
dspPickStatusTip(FRM_Task_BLL.UserTip.Stop);
if (timerPick != null)
{
//由于间隔第一次分配时间和预期时间难以管理所以这里开始跟换时间
timerPick.Change(-1, -1);
timerPick.Dispose();
GC.Collect();
}
//暂停计时操作
TMSI_Child_Run.Enabled = true;
}
#endregion
#region(窗体事件)
private void FRM_Task_FormClosing(object sender, FormClosingEventArgs e)
{
//关闭窗口的原因说明,如果是父窗体关闭,即子窗体无条件关闭。
if (e.CloseReason == CloseReason.MdiFormClosing)
{
e.Cancel = false;
}
else
{
Form frmClose = FormFactory.CreatFormObj(FormFactory.FormName.FRM_Close);
frmClose.StartPosition = FormStartPosition.CenterScreen;
if (ConfigurationManager.AppSettings["ClosePWD"] != null
&&
ConfigurationManager.AppSettings["ClosePWD"].ToString() != string.Empty)
{
if (DialogResult.Yes != frmClose.ShowDialog())
{
e.Cancel = true;
}
}
}
}
private void FRM_Task_FormClosed(object sender, FormClosedEventArgs e)
{
if (timerPick != null)
{
timerPick.Dispose();
}
//由于关闭子窗体所以向父窗体登记自己方便之后再次打开
FRM_Main.ALConnectionDBC.Add(this.Name);
}
#endregion
#region(绑定数据)
/// <summary>
/// 用System.Threading.Timer绑定数据库数据
/// </summary>
/// <param name="objValue">无效果的参数</param>
public void GetOMCDate(object objValue)
{
//怕时间间隔太小导致多次进入
//timerPick.Change(-1,-1);
dspPickStatusTip.Invoke(FRM_Task_BLL.UserTip.Pick);
if(strFormatPickTime=="")
strFormatPickTime = DateTime.Now.ToString("yyyy-MM-dd HH:00:00");
string strRTBValue = "";
try
{
if (ftbOMC.IsConnection)
{
//获取Oracle数据库数据集
DataTable dtOMCData = null;
dtOMCData = ftbOMC.dsOracleCollacte(_ServerName, strFormatPickTime).Tables[0];
ftbOMC.ImportSQLDataBase("T_CellParameter_G", dtOMCData);
strRTBValue = "[server=" + _ServerName + "]-[status=RIGHT]-[description=采集总数" + dtOMCData.Rows.Count.ToString() + "]-[time=" + strFormatPickTime + "]/r/n";
}
}
catch (Exception ex)
{
strRTBValue = "[server=" + _ServerName + "]-[status=ERROR]-[description=" + ex.Message + "]-[time=" + strFormatPickTime + "]/r/n";
//记录日志文件
ftbOMC.WritLog(strPickFilePath, strRTBValue);
}
//在屏幕上返回结果给客户看
dspOutPutPickWork.Invoke(strRTBValue+"/r/n");
//Thread.Sleep(1000);
//状态栏上消息提示
dspPickStatusTip.Invoke(FRM_Task_BLL.UserTip.Wait);
//任务完成恢复计时器
timerPick.Change(lPeriodTime,0);
}