I have a windows Service that start some tasks based on a configuration.
Each task start on its own thread, some tasks runes once per day.
I'm using Thread.Sleep()
and calculate the time for the next run.
The problem is that sometimes after 2 or 3 days the service is still running but some tasks just dont run.
The sleep period is right, everything is working fine and I am not getting any exceptions.
Is there anything that could make a thread stop or the sleep method abort the thread?
this is the main function of the thread
private void TaskLifeCycle()
{
try
{
// Creat开发者_Python百科e task object.
Type taskType = Type.GetType(this.ConfigurationElement.Task);
DebtLogic.Service.BackgroundTask bgTask = Activator.CreateInstance(taskType) as BackgroundTask;
bgTask.Context = this;
FireEvent(CreatedEventKey, new BackgroundTaskEventArgs(bgTask));
FireEvent(InitilizingEventKey, new BackgroundTaskEventArgs(bgTask));
bgTask.Initilize();
FireEvent(InitilizedEventKey, new BackgroundTaskEventArgs(bgTask));
// while the thread is alive, and did not abort then run.
while (this.CurrentThread.IsAlive)
{
try
{
//can run then block
if (CanRun(bgTask))
{
Run(bgTask);
}
}
catch (ThreadAbortException)
{
return;
}
catch (Exception ex)
{
FireEvent(ErrorEventKey,new BackgroundTaskErrorArgs(ex) );
}
}
bgTask.Dispose();
}
catch (ThreadAbortException)
{
return;
}
catch (Exception ex)
{
FireEvent(ErrorEventKey, new BackgroundTaskErrorArgs(ex));
}
}
private bool CanRun(BackgroundTask bgTask)
{
if (this.ConfigurationElement.EventBasedTask)
{
return bgTask.CanRun();
}
TimeSpan time;
if (this.ConfigurationElement.Time != TimeSpan.Zero)
{
time = this.ConfigurationElement.Time - DateTime.Now.TimeOfDay;
if (time.TotalMilliseconds < 0)
time = time.Add(new TimeSpan(24, 0, 0));
}
else
{
time = new TimeSpan(0, 0, this.ConfigurationElement.Interval);
}
Thread.Sleep(time);
return bgTask.CanRun();
}
the Run and Initialize methods are abstract methods that calls the task
Instead of having a thread that sleeps for a long time. Make a short thread that sleeps a very short time (1 minute) and each time checks if enough time has passed since the last execution. This is much more robust and lets you track if your system is 'still alive'
I'm not sure if OS
let you for such a long sleep. Either it was possible you need to change your design. A slept thread at least consumes ~1 MB of RAM (for it's context).
Try using System.Threading.Timer
or implement your own scheduling class with your requirements.
精彩评论