2013-03-06 78 views
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 
+3

你看上去遍歷一個閉包變量。嘗試將計劃分配給循環內的臨時變量並使用該變量。 – Alex 2013-03-06 11:09:36

+0

似乎關閉問題,嘗試聲明任務的本地'IJobSchedule capturedSchedule = schedule;'並使用它 – sll 2013-03-06 11:13:19

回答

5

如果你在foreach循環中使用一個臨時變量,它應該可以解決你的問題。

foreach (IJobSchedule schedule in _schedules) 
{ 
    var tmpSchedule = schedule; 
    if (tmpSchedule.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(tmpSchedule.Name); 
            JobRunner jobRunner = new JobRunner(job, tmpSchedule); 
            jobRunner.Run(); 
           }, 
           CancellationToken.None, 
           TaskCreationOptions.LongRunning, 
           TaskScheduler.Default 
           ); 
    } 


} // 

有關封鎖和循環變量進一步參考,見 Closing over the loop variable considered harmful

相關問題