4
這是一個有趣的事情。我有一個服務創建一堆Task
s。目前在列表中只配置了兩項任務。但是,如果我在Task
操作中放置斷點並檢查schedule.Name
的值,則會以相同的計劃名稱命中兩次。但是,兩個單獨的時間表已配置並在時間表列表中。任何人都可以解釋爲什麼Task重用循環中的最後一個時間表?這是一個範圍問題?運行多個任務可重複使用同一個對象實例
// make sure that we can log any exceptions thrown by the tasks
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
// kick off all enabled tasks
foreach (IJobSchedule schedule in _schedules)
{
if (schedule.Enabled)
{
Task.Factory.StartNew(() =>
{
// breakpoint at line below. Inspecting "schedule.Name" always returns the name
// of the last schedule in the list. List contains 2 separate schedule items.
IJob job = _kernel.Get<JobFactory>().CreateJob(schedule.Name);
JobRunner jobRunner = new JobRunner(job, schedule);
jobRunner.Run();
},
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default
);
}
} // next schedule
你看上去遍歷一個閉包變量。嘗試將計劃分配給循環內的臨時變量並使用該變量。 – Alex 2013-03-06 11:09:36
似乎關閉問題,嘗試聲明任務的本地'IJobSchedule capturedSchedule = schedule;'並使用它 – sll 2013-03-06 11:13:19