我正在使用 Threading.Timer 每小时执行一个任务,但是当计时器滴答时,应用程序在处理要在滴答中执行的代码时总是崩溃。它崩溃了,没有异常或警告,即使我把整个薄放在一个 try/catch 中。很奇怪。以下是我的设置,任何帮助将不胜感激!尝试访问 TextBox 时似乎崩溃了GrepCmdTextBox
,但我认为从另一个线程读取是可以的,只是不写入。
设置定时器:
var timeOfDay = DateTime.Now.TimeOfDay;
var nextHour = TimeSpan.FromHours(Math.Ceiling(timeOfDay.TotalHours));
var delta = (nextHour - timeOfDay).TotalMilliseconds;
System.Threading.Timer NextHourTimer = new System.Threading.Timer(new System.Threading.TimerCallback(NextHourTimer_Tick), null, (long)delta, (long)TimeSpan.FromHours(1).TotalMilliseconds);
勾选事件:
private void NextHourTimer_Tick(object sender)
{
// If thread is not null and is busy, cancel and restart
if (MonitoringThread != null)
{
if (MonitoringThread.TailThread.IsBusy)
{
MonitoringThread.TailThread.CancelAsync();
System.Threading.Thread.Sleep(50);
// Get grep command, if specified
string optionalGrep = String.Empty;
if (GrepCmdTextBox.Text.StartsWith("grep") || GrepCmdTextBox.Text.StartsWith("egrep"))
optionalGrep = " | " + GrepCmdTextBox.Text;
MonitoringThread.TailThread.RunWorkerAsync(optionalGrep);
}
}
}