我試圖使用並行任務庫揭開序幕像這樣的一些任務:並行任務的建議
var workTasks = _schedules.Where(x => x.Task.Enabled);
_tasks = new Task[workTasks.Count()];
_cancellationTokenSource = new CancellationTokenSource();
_cancellationTokenSource.Token.ThrowIfCancellationRequested();
int i = 0;
foreach (var schedule in _schedules.Where(x => x.Task.Enabled))
{
_log.InfoFormat("Reading task information for task {0}", schedule.Task.Name);
if(!schedule.Task.Enabled)
{
_log.InfoFormat("task {0} disabled.", schedule.Task.Name);
i++;
continue;
}
schedule.Task.ServiceStarted = true;
_tasks[i] = Task.Factory.StartNew(() =>
schedule.Task.Run()
, _cancellationTokenSource.Token);
i++;
_log.InfoFormat("task {0} has been added to the worker threads and has been started.", schedule.Task.Name);
}
我想這些任務睡覺,然後醒來每隔5分鐘,做自己的東西,在我的日程安排對象,它的運行方法,使用了Thread.Sleep的時刻是傳遞到StartNew作爲這樣一個變量的操作:
_tasks[i] = Task.Factory.StartNew(() =>
schedule.Task.Run()
, _cancellationTokenSource.Token);
我聽說了Thread.Sleep是一個不好解決這個。任何人都可以推薦更好的方法?
您可以指定TaskCreationOptions.LongRunning,創建一個新的線程,而不是使用線程池的任務。 – 2012-08-20 09:37:15