异步委托调用方法示例
ThreadPool.QueueUserWorkItem((obj) => { if (InvokeRequired && IsHandleCreated) { this.BeginInvoke(new Action<object>(delegate(object arg) { // Threads(); setText(); }), new object[] { null }); } }); public void setText() { this.textBox1.Text = "45"; }
ExecEventHandler((obj, args) => { ExecProcDomainJX(Month, falg); }, 500); private void ExecProcDomainJX(string Month, int flag) { string StrSql_1 = "EXEC PLMS_AInsertTB_DomainJX N'" + SessionAuth.UserName + "',N'" + Month + "'," + flag + ""; MyStyleControl.Win.MyWinSrv.ExecuteNonQuery(StrSql_1, new object[] { }); }
时间倒计时功能 以前有用过Timer定时器来执行,每隔一秒执行,个人认为这样会增加程序开销,最近做公司的考试模块答题时需要显示倒计时,网上搜索了下,觉得下面这个方法比较好,如下:
ThreadPool.QueueUserWorkItem((arg) => { TimeSpan TS = endDate - WinSrv.ServerDateTime; while (true) { Thread.Sleep(1000); if (TS.TotalSeconds >= 0) { if (!this.IsHandleCreated) return; this.BeginInvoke((EventHandler)delegate { lblTime.Text = quesMsg + string.Format("; 剩余{0}天{1}时{2}分{3}秒", TS.Days, TS.Hours, TS.Minutes, TS.Seconds);
this.panel.focus();//当前panel重新获取焦点 要不然每次倒计时的时候 界面会回滚到最前面 }); } if (TS.TotalSeconds == 0) //考试时间到 自动提交 { this.Invoke((EventHandler)delegate { this.btn_Submit_Click(null, null); }); } TS = AddSeconds(TS, -1); } });
private static TimeSpan AddSeconds(TimeSpan ts, int seconds)
{
return ts.Add(new TimeSpan(0, 0, seconds));
}