运行多个任务会重用相同的对象实例

时间:2013-03-06 11:06:31

标签: c# concurrency task

这是一个有趣的。我有一个服务创建了一堆Task。目前,列表中只配置了两个任务。但是,如果我在Task操作中放置一个断点并检查schedule.Name的值,则会使用相同的计划名称命中两次。但是,会在计划列表中配置两个单独的计划。任何人都可以解释为什么任务重用循环中的最后一个计划?这是范围问题吗?

// 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

1 个答案:

答案 0 :(得分: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