日期:2014-05-17 浏览次数:21159 次
<!--发送频率限制(秒)--> <add key="MsgTimeLimit" value="10"/> <!--上次最后发送时间--> <add key="LastMsgTime" value="2013-11-1"/>Test.cs
CancellationTokenSource ct; private void btnOK_Click(object sender, EventArgs e) { btnOK.Enabled = false; Task t = new Task(() => Do(ct)); ct = new CancellationTokenSource(); t.Start(); t.ContinueWith((x) => { this.SafeCall(() => { richTextBox1.AppendText("任务结束\r\n"); btnOK.Enabled = true; }); }); } private void btnCancel_Click(object sender, EventArgs e) { ct.Cancel(); } /// <summary> /// 获取发送剩余的时间 /// </summary> /// <returns></returns> private int GetMsgRestSeconds() { int msgTimeLimit = 0; //获取要限制的间隔时间(秒) int.TryParse(AppSettings.GetValue("MsgTimeLimit"), out msgTimeLimit); if (msgTimeLimit == 0) return 0; //最近一次时间 string lastMsgTime = AppSettings.GetValue("LastMsgTime"); DateTime dtLastMsgTime = DateTime.MinValue; DateTime.TryParse(lastMsgTime, out dtLastMsgTime); DateTime dtNow = DateTime.Now; if (dtLastMsgTime == DateTime.MinValue || dtLastMsgTime >= dtNow) return 0; TimeSpan ts = dtNow - dtLastMsgTime; int restSeconds = 0; if (msgTimeLimit > ts.TotalSeconds) { restSeconds = msgTimeLimit - (int)ts.TotalSeconds; restSeconds = restSeconds < 0 ? 0 : restSeconds; } return restSeconds; }
其中
AppSettings.SetValue()和AppSettings.GetValue()方法见:
http://blog.csdn.net/gdjlc/article/details/8284799
SafeCall是个扩展方法
public static void SafeCall(this Control ctrl, Action callback)
{
if (ctrl.InvokeRequired)
ctrl.Invoke(callback);
else
callback();
}